I have this regex that matches something like [abc]
as a string pattern, with the help of"[]": "((\\[[^\\]]*($|\\]))(\\][^\\]]*($|\\]))*)
So it will catch [ABC]
from ABC AB [ABC] BC
. So anything enclosed in a square bracket.
It works as it's supposed to.
Then I wrote an expression like"{{}}": "((\\{\\{[^\\}\\}]*($|\\}\\}))(\\}\\}[^\\}\\}]*($|\\}\\}))*)"
to catch something like {{abc}}
. Now, this does work in online regex testers, it catches {{abc}}
from ABC AB {{ABC}} BC
.
But it's not doing anything when I have it in a JS code. While, the square bracket expression does what it's supposed to. Am I missing something?
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('|');
}
This is the whole snippet surrounding this
I don't see the problem. I also tried to use your code and it seems to work:
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.