簡體   English   中英

Javascript 正則表達式替換字符如果前面和后面是一個字母

[英]Javascript regex replace character if preceded AND followed by a letter

基本上我正在使用一個字符串,它是一個 json 字符串,我想把它變成一個真正的 json (通過使用 JSON.parse())但是句子中間有一些引號。

示例:'{"author":"Jonah D"Almeida", ... }'(我想替換 D 和 Almeida 之間的那個)

由於整個句子周圍已經有引號,javascript 給出錯誤,因為它無法從中創建 json 等,為了解決這個問題,基本上我想將句子中間的引號替換為 ' 但是僅當它在引號前后有字母時。

我的想法: myString.replace('letter before... "... letter after', "'")

知道我怎樣才能得到正確的表達嗎? 基本上我只想知道正則表達式檢查是否在 " 引用之前和之后是否有字母。

OP ... “基本上我正在使用 json 字符串”

上面的示例不是 OP 所指的json string OP 的示例數據字符串已經無效 JSON。

因此,第一件事是修復生成此類數據的過程。

因為...

“解析有效的 JSON 數據將返回一個完全有效的 object,如果是 OP 的用例,還會返回一個正確轉義的字符串值。”

... 證明...

 const testSample_A = { author: "Jonah D'Almeida" }; const testSample_B = { author: 'Jonah D"Almeida' }; const testSample_C = { author: 'Jonah D\'Almeida' }; const testSample_D = { author: "Jonah D\"Almeida" }; console.log({ testSample_A, testSample_B, testSample_C, testSample_D, }); console.log('JSON.stringify(...)... ', { testSample_A: JSON.stringify(testSample_A), testSample_B: JSON.stringify(testSample_B), testSample_C: JSON.stringify(testSample_C), testSample_D: JSON.stringify(testSample_D), }); console.log('JSON.parse(JSON.stringify(...))... ', { testSample_A: JSON.parse(JSON.stringify(testSample_A)), testSample_B: JSON.parse(JSON.stringify(testSample_B)), testSample_C: JSON.parse(JSON.stringify(testSample_C)), testSample_D: JSON.parse(JSON.stringify(testSample_D)), });
 .as-console-wrapper { min-height: 100%;important: top; 0; }

編輯

盡管如此,仍然可以基於正則表達式來實現完全遵循 OP 要求的清理任務,該正則表達式具有積極的 前瞻和積極的 后瞻......僅適用於基本拉丁語/(?<=\w)"(?=\w)/gm或更多國際化unicode 轉義... /(?<=\p{L})"(?=\p{L})/gmu

 console.log('Letter unicode escapes...', ` {"author": "Jonah D"Almeida", ... } {"author": "Jon"ah D"Almeida", ... } {"author": "Jon"ah D"Alme"ida", ... }`.replace(/(?<=\p{L})"(?=\p{L})/gmu, '\\"') ); console.log('Basic Latin support...', ` {"author": "Jonah D"Almeida", ... } {"author": "Jon"ah D"Almeida", ... } {"author": "Jon"ah D"Alme"ida", ... }`.replace(/(?<=\w)"(?=\w)/gm, '\\"') ); console.log( 'sanitized and parsed string data...', JSON.parse(`[ { "author": "Jonah D"Almeida" }, { "author": "Jon"ah D"Almeida" }, { "author": "Jon"ah D"Alme"ida" } ]`.replace(/(?<=\p{L})"(?=\p{L})/gmu, '\\"')) );
 .as-console-wrapper { min-height: 100%;important: top; 0; }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM