Use static string once in Regex while using two patterns with OR

942 Views Asked by At

Here is my regex:

STATICSTRING\s[a-zA-Z]:\\[\\\S|*\S]?.*$|STATICSTRING\s\w*

as you can see there are two patterns, \s[a-zA-Z]:\\[\\\S|*\S]?.*$ and \s\w* which is combined with a | operator. and the STATICSTRING is repeated in each one.

Is there any way to write STATICSTRING once?

1

There are 1 best solutions below

16
On BEST ANSWER

You may use an | alternation operator in a grouping construct to group two subpatterns:

STATICSTRING\s(?:[a-zA-Z]:\\[\\\S|*\S]?.*$|\w*)
              ^^^                         ^   ^

However, the \\[\\\S|*\S]?.* part looks like a user error. It matches a \, then 1 or 0 occurrences of \, |, * or any non-whitespace char, and then .* matches any 0+ chars up to the end of the line. Make sure you fix it if you intended to match anything else. But \w* branch will always "win" as it always matches (either an empty string or a letter (and [a-zA-Z] also matches a letter)). So, the pattern above is equal to STATICSTRING\s\w*.