Search code examples
regexpcre

Regex to return numeric value if it match one string or the other


I have a string which can come in two different ways. See the example below:

# Option 1
Court Case Fee $214.00

# Option 2
Court Filing Fee: Contract $198.00

I want to build a RegEx that will return the first amount without the dollar sign. For example:

  • if the string is the Option 1: 214.00
  • if the string is the Option 2: 198.00

I have built this RegEx:

/Court Case Fee|Court Filing Fee: Contract \$(?<court_case_fee>\d+\.\d+)/mi

But is not working since it just returns the value for Option 2. What I am missing here?

Here is the Regex101 so you can play with it: https://regex101.com/r/Od3r6y/1


Solution

  • You can use a non capture group (?: for both the alternatives, and optionally match Contract

    Perhaps start the pattern with a word boundary \b to prevent a partial word match.

    \bCourt (?:Case Fee|Filing Fee:) (?:Contract )?\$(?<court_case_fee>\d+\.\d+)
    

    Regex demo

    Or the pcre version with a match only, where \h+ matches 1 or more horizontal whitespace chars and \K forgets what is matched so far:

    \bCourt\h+(?:Case\h+Fee|Filing Fee:)\h+(?:Contract\h+)?\$\K\d+\.\d+
    

    Regex demo