Search code examples
regexregex-lookaroundsregex-negationregex-groupregex-greedy

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.


Solution

  • Use this regex

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

    and capture group 1 (inside the braces).

    See this regex101 test