简体   繁体   English

匹配正则表达式直到第一次出现特殊字符'->'

[英]Match regex until the first occurrence of special character '->'

I am a newbie to regexp and was trying to match the expression until a special character/s.我是 regexp 的新手,并试图匹配表达式直到一个特殊字符/s。 If the matches exist before the special character then return it otherwise return nothing.如果匹配项在特殊字符之前存在,则返回它,否则不返回任何内容。

Here is the demo .这是演示

My goal is to return the match if found before the '->' special character otherwise return nothing.如果在“->”特殊字符之前找到匹配项,我的目标是返回匹配项,否则不返回任何内容。 It should not return the matches after the '->' special char.它不应该在 '->' 特殊字符之后返回匹配项。

Regexp: /()()(\[[^\]]+\])\s*(-[->])(.*)/g // In third group actual result will be returned正则表达式: /()()(\[[^\]]+\])\s*(-[->])(.*)/g // 第三组返回实际结果

For example data:例如数据:

[AAA] -> [BBB] -> [CCC] // In this case needs to match [AAA] [AAA] -> [BBB] -> [CCC] // 这种情况下需要匹配 [AAA]

AAA -> [BBB] -> [CCC] // In this case do not return [BBB], instead return nothing as before special char '->', no matchng is there. AAA -> [BBB] -> [CCC] // 在这种情况下不返回 [BBB],而是像以前一样不返回任何内容特殊字符 '->',不存在匹配项。

Please help me with this.请帮我解决一下这个。 Thanks in advance.提前致谢。

Use this regex使用这个正则表达式

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

and capture group 1 (inside the braces).并捕获第 1 组(大括号内)。

See this regex101 test请参阅此 regex101 测试

Is this what you want?这是你想要的吗?

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

Explanation:解释:

^               # 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演示

I don't fully understand the problem, just copying a few guessworks in here, that might get you closer to what you're trying to accomplish:我不完全理解这个问题,只是在这里复制一些猜测,这可能会让你更接近你想要完成的事情:

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

Demo 1演示 1

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

Demo 2演示 2

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

Demo 3演示 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}`); }); }

RegEx Circuit正则表达式电路

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

在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM