[英]Regex involving curly braces not working, while for square brackets it does
我有這個正則表達式匹配類似[abc]
作為字符串模式,在"[]": "((\\[[^\\]]*($|\\]))(\\][^\\]]*($|\\]))*)
所以它會從ABC AB [ABC] BC
中捕獲[ABC]
。 所以任何東西都包含在方括號中。
它按預期工作。
然后我寫了一個表達式"{{}}": "((\\{\\{[^\\}\\}]*($|\\}\\}))(\\}\\}[^\\}\\}]*($|\\}\\}))*)"
捕捉像{{abc}}
這樣的東西。 現在,這確實適用於在線正則表達式測試器,它從ABC AB {{ABC}} BC
捕獲{{abc}}
。
但是當我在 JS 代碼中使用它時,它什么也沒做。 同時,方括號表達式做了它應該做的事情。 我錯過了什么嗎?
createStringRegex(stringTypes) {
return new RegExp('^(' + this.createStringPattern(stringTypes) + ')', 'u');
}
// This enables the following string patterns:
// 1. backtick quoted string using `` to escape
// 2. square bracket quoted string (SQL Server) using ]] to escape
// 3. double quoted string using "" or \" to escape
createStringPattern(stringTypes) {
const patterns = {
'``': '((`[^`]*($|`))+)',
'[]': '((\\[[^\\]]*($|\\]))(\\][^\\]]*($|\\]))*)',
"{{}}": "((\\{\\{[^\\}\\}]*($|\\}\\}))(\\}\\}[^\\}\\}]*($|\\}\\}))*)",
'""': '(("[^"\\\\]*(?:\\\\.[^"\\\\]*)*("|$))+)',
"''": "(('[^'\\\\]*(?:\\\\.[^'\\\\]*)*('|$))+)",
"N''": "((N'[^N'\\\\]*(?:\\\\.[^N'\\\\]*)*('|$))+)"
};
return stringTypes.map(t => patterns[t]).join('|');
}
這是圍繞這個的整個片段
我沒有看到問題。 我也嘗試使用你的代碼,它似乎工作:
function createStringRegex(stringTypes) { return new RegExp('^(' + this.createStringPattern(stringTypes) + ')', 'u'); } // This enables the following string patterns: // 1. backtick quoted string using `` to escape // 2. square bracket quoted string (SQL Server) using ]] to escape // 3. double quoted string using "" or \" to escape function createStringPattern(stringTypes) { const patterns = { '``': '((`[^`]*($|`))+)', '[]': '((\\[[^\\]]*($|\\]))(\\][^\\]]*($|\\]))*)', "{{}}": "((\\{\\{[^\\}\\}]*($|\\}\\}))(\\}\\}[^\\}\\}]*($|\\}\\}))*)", '""': '(("[^"\\\\]*(?:\\\\.[^"\\\\]*)*("|$))+)', "''": "(('[^'\\\\]*(?:\\\\.[^'\\\\]*)*('|$))+)", "N''": "((N'[^N'\\\\]*(?:\\\\.[^N'\\\\]*)*('|$))+)" }; return stringTypes.map(t => patterns[t]).join('|'); } console.log("[abc]".match(createStringRegex(["[]"]))); // it matches console.log("{{abc}}".match(createStringRegex(["{{}}"]))); // it matches console.log("[abc]".match(createStringRegex(["{{}}"]))); // it doesn't match
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.