下面的正則運算式應該找到 的所有匹配項${any expression},代碼如下:
const reg= /\$\{[^] \}/g
let txt= '`${i " test"} RESULT ${2 4} now ${i} hi`'
let result= [...txt.matchAll(reg)];
console.log(result)
正如您會注意到的,結果是它幾乎提取了整個字串,正確的操作應該在控制臺中列印一個包含 3 個元素的陣列,其中包含${any expression}
以下案例顯示了我使用時生成的錯誤:[^}]
const reg= /\$\{[^}] \}/g
let i= "some"
let txt= `${i " test"} RESULT ${2 4} now ${i "}" } hi`
let txtString= '`${i " test"} RESULT ${2 4} now ${i "}" } hi`'
let result= [...txtString.matchAll(reg)];
console.log(result)
console.log(txt)
該運算式${i "}" }在 JavaScript 中有效,因此正則運算式應回傳[${i "}" }, other matches],但在所示示例中它回傳
${i "}
uj5u.com熱心網友回復:
如果您可以在內部描述令牌語法,${...}您仍然可以使用正則運算式。
如果我們假設
- 比賽開始于
${ - 里面的標記可以用零個或多個空格分隔
- 標記是分隔的
,-,*或/運算子 - 標記可以是單詞字串(字母、數字、下劃線)或雙引號字串文字 (
"...\"...\\...") - 比賽以
}
然后你可以使用
const reg= /\${\s*(?:\w |"[^"\\]*(?:\\[^][^"\\]*)*")(?:\s*[- \/*]\s*(?:\w |"[^"\\]*(?:\\[^][^"\\]*)*"))*\s*}/g
請參閱正則運算式演示。
請參閱 JavaScript 演示:
const token = '(?:\\w |"[^"\\\\]*(?:\\\\[^][^"\\\\]*)*")';
const op = '[- /*]';
const reg= new RegExp(String.raw`\${\s*${token}(?:\s*${op}\s*${token})*\s*}`, 'g');
let i= "some"
let txt= `${i " test"} RESULT ${2 4} now ${i "}" } hi`
let txtString= '`${i " test"} RESULT ${2 4} now ${i "}" } hi`'
let result= [...txtString.matchAll(reg)];
console.log(result)
console.log(txt)
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/476790.html
標籤:javascript 正则表达式
