【问题标题】:Match regex until the first occurrence of special character '->'匹配正则表达式直到第一次出现特殊字符'->'
【发布时间】:2019-10-06 18:11:23
【问题描述】:

我是 regexp 的新手,我一直在尝试匹配表达式,直到出现特殊字符。如果匹配项在特殊字符之前存在,则返回它,否则不返回任何内容。

这里是demo。

如果在“->”特殊字符之前找到匹配项,我的目标是返回匹配项,否则不返回任何内容。它不应该在 '->' 特殊字符之后返回匹配项。

Regexp: /()()(\[[^\]]+\])\s*(-[->])(.*)/g // 第三组返回实际结果

例如数据:

[AAA] -> [BBB] -> [CCC] //这种情况下需要匹配[AAA]

AAA -> [BBB] -> [CCC] // 在这种情况下不返回 [BBB],而是像以前一样不返回任何内容特殊字符'->',没有匹配。

请帮我解决这个问题。提前致谢。

【问题讨论】:

  • 在开头加^即可。您也可以删除 2 个空 () 组。这是简化版:regex101.com/r/6NcJBF/1
  • 感谢大家的宝贵回复。嗨,艾玛,尝试了您的第一个链接似乎符合我的目的,但出于某种目的,我需要添加两个空 ()。如果我添加它打破了比赛,你能建议一下吗? Link

标签: regex regex-lookarounds regex-negation regex-group regex-greedy


【解决方案1】:

使用这个正则表达式

^\[(.*?)\] ->

并捕获第 1 组(大括号内)。

See this regex101 test

【讨论】:

  • 谢谢你,Bob,它可以根据我的需要进行调整。
【解决方案2】:

这是你想要的吗?

^\[[^\]]+\](?=\h*->)

说明:

^               # beginning of string
  \[            # opening squarre bracket
    [^\]]+      # 1 or more any character that is not closiing bracket
  \]            # closing bracket
  (?=           # start positive lookahead, make sure we have after:
    \h*         # 0 or more horizontal spaces
    ->          # literally ->
  )             # end lookahead

Demo

【讨论】:

    【解决方案3】:

    我不完全理解这个问题,只是在这里复制一些猜测,这可能会让你更接近你想要完成的事情:

    ^()()((\[[^\]]*\]))\s*->(.*)
    

    Demo 1

    ()()(\[[^\]]+\])\s*->(\s*\[[^\]]+\]\s*->\s*\[[^\]]+\])
    

    Demo 2

    ()()(\[[^\]\r\n]+\])\s*->\s*(\[[^\]\r\n]+\]\s*->\s*\[[^\]\r\n]+\])
    

    Demo 3

    const regex = /^()()((\[[^\]]*\]))\s*(->)(.*)/gm;
    const str = `[AAA] -> [BBB] -> [CCC]
    AAA -> [BBB] -> [CCC]`;
    let m;
    
    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}`);
        });
    }

    正则表达式电路

    jex.im 可视化正则表达式:

    【讨论】:

    • 嗨@Emma,内容丰富的链接,感谢分享。
    猜你喜欢
    • 2011-01-02
    • 1970-01-01
    • 1970-01-01
    • 2016-03-18
    • 2021-11-03
    • 2022-08-18
    • 1970-01-01
    相关资源
    最近更新 更多