Skip to content Skip to sidebar Skip to footer

Regex - Find All Optional Group Occurrences

I'm creating regex in JavaScript that find all groups occurrences, all optional. I found many questions, but none of answers works for me. I'm using xregexp package, but for simpli

Solution 1:

You may use

new-(?:.*?(rooms-\d+))?.*?(area-\d+)
    ^^^^^^^^^^^^^^^^^^^

See the regex demo

The point is to make the capturing group obligatory but put it into an optional non-capturing group. The last * greedy quantifier is converted to a lazy one, but it is not necessary.

Details:

  • new- - matches an obligatory new-
  • (?:.*?(rooms-\d+))? - an optional (1 or 0 occurrences, greedy match, i.e. the regex engine will try to match the pattern of the group) sequence of:
    • .*? - any 0+ chars other than line break chars as few as possible (that is, lazy matching, the pattern is skipped and the subsequent patterns are tried first, and is only expanded once the subsequent patterns fail)
    • (rooms-\d+) - Group 1: rooms- and 1+ digits (now, it is not optional, must match or the whole non-capturing group will match an empty string)
  • .*? - any 0+ chars other than line break chars as few as possible
  • (area-\d+) - Group 2: area- and 1+ digits.

Post a Comment for "Regex - Find All Optional Group Occurrences"