Home > Mobile >  Can RegEx have an OR function
Can RegEx have an OR function

Time:11-24

I have string of text that follows the format below.

code (family) - LongName (ShortName)

I want to parse out "ShortName" and the following works

\).*\(([^\)] )\)

but if I use the above RegEx on an unformatted line of text it returns blank. I'd rather it return the unformatted string

CodePudding user response:

Your pattern is unanchored, and the match can occur in the middle of the string.

If there can be a single match, you could prepend an anchor, and in the alternation | match the whole line.

^.*\).*?\(([^\)\n] )\)|^. 

Regex demo

If there can be more matches, you could make the dot non greedy .*? to not only get the last occurence, and only match the whole line if the pattern does not occur using a negative lookahead.

\).*?\(([^\)\n] )\)|^(?!.*\).*?\(([^\)\n] )\)). 

Regex demo

  • Related