PCRE matching catching subpatterns

Viewed 62

I am embarrased I can't figure it out, so I have to ask. But let's say I have a string where I want to match one OR two words. The first word must always be matched and the second word is sometimes present and sometimes absent so it should be matched if present. If it is absent, the first word must still be matched. I.e. the whole expression must not fail if the second word is absent.

 "this <word> must always be matched and this <word1> will maybe be matched"

Naively I tried

(word).*(word1)?

but even if both words are present, only <word> is returned. If I remove the '?' both words are returned, but if <word1> then is not present "no match" is returned.

~/ % pcretest
PCRE version 8.45 2021-06-15

  re> "(word).*(word1)"
data> this is <word> and this is <word1>"
 0: word> and this is <word1
 1: word
 2: word1

  re> "(word).*(word1)?"
data> this is <word> and this is <word1>"
 0: word> and this is <word1>"
 1: word

  re> "(word).*(word1)"
data> this is <word> and this is"
No match
1 Answers

You can use

(word)(?:.*(word1))?

See the regex demo. Details:

  • (word) - a word captured into Group 1
  • (?:.*(word1))? - an optional non-capturing group matching one or zero occurrences of
    • .* - any zero or more chars other than line break chars as many as possible
    • (word1) - word1 captured into Group 2.
Related