简体   繁体   中英

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. 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

For example data:

[AAA] -> [BBB] -> [CCC] // In this case needs to match [AAA]

AAA -> [BBB] -> [CCC] // In this case do not return [BBB], instead return nothing as before special char '->', no matchng is there.

Please help me with this. Thanks in advance.

Use this regex

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

and capture group 1 (inside the braces).

See this regex101 test

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

()()(\[[^\]]+\])\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}`); }); }

RegEx Circuit

jex.im visualizes regular expressions:

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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