how do we match a string against multiple patters in PCRE ? I need to match this string
subj1 = "9112345678 put car details of the car";
patt1 = "(\\d+) ([a-z]+) ([a-z]+) (.+)";
some times the subject can be like this
subj2 = "9112345678 put car";
which is matching pattern
patt2 = "(\\d+) ([a-z]+) ([a-z]+)";
since the subject is dynamic and not known a prior would like to “or” these 2 patterns and want to match the subject against a composite pattern.
some thing like
sub matching (patt1 or patt2)
can we do this in PCRE ?
You just need to make the last chunk optional:
And if you also need to allow “9112345678 put” then add more optional groups:
If you want to maintain nice sequential references to your capture groups and if your PCRE engine really is PC, then you can use clustering groups in place of some of the capturing groups:
Thanks go to Kobi for kindly suggesting this variant. With this version, matching against:
will yield:
"9112345678"in$1"put"in$2"car"in$3"details of the car"in$4And that’s probably easier to deal with than accounting for all the extra nesting.