Home > Mobile >  Conditaionl regular expression - if a pattern exists use one regular expression and if another patte
Conditaionl regular expression - if a pattern exists use one regular expression and if another patte

Time:01-31

I got strings such as these:

'Age at death (years) 0.0'  
'Age at death 0.0'  

In both cases I need to capture Age at death.
To capture the desired string in the first example I used . (?= \(?. \)?), and for the second I used . (?= \d \.\d ). Adding | between the two in one expression didn't work as needed.
I'm looking for a way to combine the two so that they will be used conditionally for each scenario.
Thanks!

CodePudding user response:

You can use

^.*?(?=\s*[\d(])

See the regex demo.

Details:

  • ^ - start of string
  • .*? - any zero or more chars other than line break chars, as few as possible
  • (?=\s*[\d(]) - a positive lookahead that requires zero or more whitespaces and then a digit or ( immediately to the right of the current location.
  • Related