我有两个字符串:
"~if~ text_if_true ~end~"
"~if~ text_if_true ~else~ text_if_false ~end~"
我只想要一个正则表达式,并提供以下输出:
for 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}`);
});
}
答案 0 :(得分:4)
您应该使整个~else~
是可选的,而不是仅使~else~ (.*?)
这个单词为可选(我还添加了一些空格,以便这些组没有前导或尾随空格):< / p>
if~ (.*?)(?: ~else~ (.*?))? ~end
答案 1 :(得分:1)
您可以将~else~ text_if_false
部分设为可选,如下例所示。
var input = ["~if~ text_if_true ~end~",
"~if~ text_if_true ~else~ text_if_false ~end~"];
var re = /~if~ (.*?)(?: ~else~ (.*?))? ~end~/
for(var i=0;i<input.length;i++)
console.log(input[i].match(re));