javascript - "IF textTrue ELSE textFalse"的正则表达式

标签 javascript regex

我有两个字符串:

"~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_truetext_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}`);
    });
}

最佳答案

与其让~else~这个词可选,不如让整个~else~(.*?)可选(我还添加了一些空格这样组就没有前导或尾随空格):

if~ (.*?)(?: ~else~ (.*?))? ~end

Demo

关于javascript - "IF textTrue ELSE textFalse"的正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57770630/

相关文章:

javascript - 有缺陷的二叉树

javascript - 带有 2 个过滤器的 JQuery 画廊

javascript - 如果 GET 请求返回 404 错误,则中断 javascript 链

CSS 字段名属性掩码

regex - 删除所有直到并包括三重换行符的内容

javascript - 使用 Javascript 单击时显示 1 个 div 并隐藏所有其他 div

javascript - 选择列表不保留所选值

regex - 为什么这个 grep 命令没有返回任何东西? ( bash )

javascript - 如何在nodejs中使用express get route从url中提取页面名称和authToken?

regex - 从postgres中的文本字符串中提取子字符串