random
random

Reputation: 194

Conditional regular expression - if a pattern exists use one regular expression and if another pattern exists use another regular expression

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.

More examples

'Weight (pre-imaging) (Kg) 1.0'
'Body mass index (BMI) more text to be captured (Kg/m2) 0.0'

In these examples the first parentheses in each sentence need to be captured rather than omitted.

Upvotes: 2

Views: 75

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627145

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.

Upvotes: 1

Related Questions