Search code examples
regexregex-group

Regex to capture string with two rules


I have the following regex that should be capturing 1 group on the first phrase, and three groups on the second phrase. But for some reason, when I add the optional group with the two right groups, it does not capture string one.

regex (case insensitive)

(^(?<FULLTEXT>.*))\s?(?:(?<AREA>[a-z]{4,4}).(?<SQRM>[\d]+))$

phrases

MASTER BEDROOM

LIVING ROOM LVRM 103

Phrases will always be: 1 - full text 2 - ends with AREA - which is 4 character string (always) + SQRM 3 digit (always). Anything before that is the fulltext.

Sentence #2 captures: FULLTEXT - LIVING ROOM AREA - LVRM SQRM - 103

Sentence #1 SHOULD capture FULLTEXT only, but it captures nothing....

Any suggestion is appreciated.


Solution

  • You may use

    ^(?<FULLTEXT>.*?)\s*(?:(?<AREA>[a-z]{4})\s*(?<SQRM>\d+))?$
    

    See the regex demo

    Details

    • ^ - start of string
    • (?<FULLTEXT>.*?) - Group "FULLTEXT": any 0 or more chars other than line break chars, as few as possible
    • \s* - 0+ whitespaces
    • (?:(?<AREA>[a-z]{4})\s*(?<SQRM>\d+))? - an optional sequence of
      • (?<AREA>[a-z]{4}) - Group "AREA": four letters
      • \s* - 0+ whitespaces
      • (?<SQRM>\d+) - Group "SQRM": 1+ digits
    • $ - end of string.