Conditional matching
Today, while proving what a prat I am, I added some conditional testing to a pattern which I had written. Conditional matching allows you to perform a test based on if...then[...else] logic. The syntax is (?if then | else ) - with the 'else' part being optional.
To demonstrate, given the following 2 words:
Thursday Thurday
I only want to match the 'day' part if the 's' has been matched so. First I come up with a pattern like so to match 'Thur' and an optional 's':
Thur(s)?
and then add a bit to match day at the end:
Thur(s)?(day)?
This will match: 'Thur' and 'Thursday' but, will also allow 'Thurday'; this is where the conditional matching comes in. First, I'll turn on ExplicitCapture and place the optional 's' capture into a named group:
(?n)(Thur(?'checkFor's)?)
Now, I can add conditional logic to the 'day' match like so:
(?n)(Thur(?'checkFor's)?)(?(1)day)?To demonstrate how to use the "else" part of the conditional, let's say that we can also match words that fail the test but end in 'foo'; so I add the else part to the regex like so:
(?n)(Thur(?'checkFor's)?)(?(1)day|foo)?
Which would now also match the word: 'Thurfoo'!