我需要选择在双圆括号和双大括号之间的值,但是允许使用非双大括号和圆括号。我使用了以下表达式来匹配双大括号,但如果字符串中有大括号,它就会出错。应该仅通过双大括号来中断,但我不知道如何制作正则表达式。
/{{([^}]*)}}/g
并且
/\({2}([^)]*)\){2}/g
我试过在这里添加双括号,但它没有起作用:
/{{([^}}]*)}}/g
/{{([^}]*)}}/g
并且
/\({2}([^)]*)\){2}/g
我试过在这里添加双括号,但它没有起作用:
/{{([^}}]*)}}/g
因为您希望允许单个大括号,所以不应使用负字符集-相反,应从左分隔符开始,懒惰重复任何字符,直到到达右分隔符。例如:
/{{(.*?)}}/
const pattern = /{{(.*?)}}/g;
const str = 'foo{{bar}} foo{{baz}} foo{{with}bracket}}';
console.log(str.match(pattern));
我认为您在括号中缺少反斜杠。
也许像/\{\{([^)]+)\}\}/
这样的表达式会起作用。
示例:
console.log("{{TEST}}".match(/\{\{([^)]+)\}\}/)[1]);
console.log("{{TE{{}}ST}}".match(/\{\{([^)]+)\}\}/)[1]);
@certainperformance 所说的是正确的。 我只想为你在问题中提到的括号和大括号添加一个表达式。
**你可以尝试这个表达式来匹配括号和大括号**
((?:{{)(.*?}}))|((?:\(\()(.*?\)\)))
const regex = /((?:{{)(.*?}}))|((?:\(\()(.*?\)\)))/gm;
const str = `foo{{bar}} foo{{baz}} foo{{with}bracket}}
foo((hello))
test{{test))
{{test))
{{test}}
((test))
test))
`;
let m;
let op = str.match(regex);
console.log(op);
{{test}}
- The fourth bird
{{stringhaving{{doublebraces}}}
是否被允许? - vrintle