我有两个字符串:
"~if~ text_if_true ~end~"
"~if~ text_if_true ~else~ text_if_false ~end~"
我想要的只是一个具有以下输出的正则表达式:
对于 1.=>
group 1 = text_if_true
对于 2.=>
group 1 = text_if_true, group 2 = text_if_false
我试过:
~if~(.*?)(?:~else~)(.*?)~end~
在 II 上工作正常但在 I 上不行,因为需要 ~else~
如果我用
~if~(.*?)(?:~else~)?(.*?)~end~
在 (?:~else~)
后面有一个 ?
(对于 0 或 1 个匹配项) text_if_true
和 text_if_false
在第一组。
有解决问题的简单方法吗?
const regex = /~if~(.*?)(?:~else~)(.*?)~end~/gm;
const regex2 = /~if~(.*?)(?:~else~)?(.*?)~end~/gm;
const str = `~if~ text_if_true ~else~ text_if_false ~end~
~if~ text_if_true ~end~`;
let m;
console.log('without ? quantifier')
while ((m = regex.exec(str)) !== null) {
// This is necessary to avoid infinite loops with zero-width matches
if (m.index === regex.lastIndex) {
regex.lastIndex++;
}
// The result can be accessed through the `m`-variable.
m.forEach((match, groupIndex) => {
console.log(`Found match, group ${groupIndex}: ${match}`);
});
}
console.log('with ? quantifier')
while ((m = regex2.exec(str)) !== null) {
// This is necessary to avoid infinite loops with zero-width matches
if (m.index === regex.lastIndex) {
regex.lastIndex++;
}
// The result can be accessed through the `m`-variable.
m.forEach((match, groupIndex) => {
console.log(`Found match, group ${groupIndex}: ${match}`);
});
}
最佳答案
关于javascript - "IF textTrue ELSE textFalse"的正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57770630/