Search code examples
phpregexpcre

How to improve the regex?


I'm trying to match the following possibilities with a regex:

MORE THAN CAD 10,000
MORE THAN CAD 10,000 BUT LESS THAN CAD 15,000
LESS THAN CAD 10,000

My regex works with /^(((MORE|LESS) THAN CAD [\d,]+)|(MORE THAN CAD [\d,]+ BUT LESS THAN CAD [\d,]+))$/ but I'm wondering if there's a more elegant way.

I've tried /^(MORE THAN CAD [\d,]+)?(( BUT )?LESS THAN CAD [\d,]+)?$/ but it's letting the following pass as well:

MORE THAN CAD 10,000LESS THAN CAD 15,000

Solution

  • You can use

    ^(?:(MORE)|LESS) THAN CAD [\d,]+(?(1)(?: BUT LESS THAN CAD [\d,]+)?)$
    

    See the regex demo.

    Details:

    • ^ - start of string
    • (?:(MORE)|LESS) - a non-capturing group matching MORE (captured in Group 1) or LESS
    • THAN CAD - a literal string
    • [\d,]+ - one or more digits or commas
    • (?(1)(?: BUT LESS THAN CAD [\d,]+)?) - a conditional that allows matching an optional BUT LESS THAN CAD [\d,]+ pattern if Group 1 matched.
    • $ - end of string.