Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Capturing optional groups in regex

Tags:

regex

I need to capture the optional texts in a pattern, with the extracted examples i, 9, Caffè and you in the following matched scenarios:

  • Valid matches:

    love!
    9 love!
    love Caffè!
    i love you!
    
  • Invalid matches:

    love
    iloveyou
    

My rule: [*] love [*]!, with [*] meaning blank text can be accepted to be captured.

I tried to make the regex ((?:.+) )?love( (?:.+))?! (online) but it failed to capture the correct texts.

like image 955
MiP Avatar asked May 24 '26 14:05

MiP


1 Answers

You may swap your capturing with non-capturing groups:

(?:(.+) )?love(?: (.+))?!
 ^^            ^^

See the regex demo

Now, the text that you will have inside groups will be without spaces as they are part of the non-capturing groups that are only meant to group subpatterns.

like image 81
Wiktor Stribiżew Avatar answered May 26 '26 05:05

Wiktor Stribiżew