Optional capture is always ignored in favor of *

Given the statement

the cat and the dog played together

I can grab both cat and dog with this regex

(cat).*(dog)

There will not always be a cat in the sentence, so I make the first capture group optional

(cat)?.*(dog)

When using an optional capture group, it .*always captures the entire first part, ignoring the optional capture, even if there is one. How can you grab a cat if it is, but if it is absent, the regular expression will still match the dog?

I tried to make the star inanimate

(cat)?.*?(dog)

and tried to use |instead of an optional capture group, but the first capture group is always ignored.

Example result, http://regex101.com/r/pR1kZ9

+4
2
(?:(cat).*)?(dog)

"cat" "" , , "cat".

http://regex101.com/r/cE9yC8

:

the cat and the dog played together  - match 'cat' and 'dog
the mouse didn't play with the dog   - match 'dog'
+2

:

(?:.*?(?=cat))?(cat)?.*(dog)

cat; , , .

the cat played with the dog    ==> 'cat', 'dog'
the mouse played with the dog  ==> 'dog'
the dog played with the cat    ==> 'dog'

: http://regex101.com/r/eT7pR4

+1

Source: https://habr.com/ru/post/1539635/


All Articles