This will be the end of this series, the last article. In contrast, embedding conditions are rarely used in regular expressions, and even many languages do not support embedding conditions, but most of all, this chapter briefly describes how embedded conditions are used in regular expressions. An expression that embeds a condition follows the instructions in the book:
? (backer-ference) True-regex|false-regex
We give an example here to build a matching US phone number example:
123-456-7890
(123) 456-7890
(123-456-7890
1234567890
123 456 7890
In general, we can write a regular expression to match the phone number.
\ (? \d{3}\)?-? \d{3}-\d{4}
According to the expression above, the third (123-456-7890 will match, and it is clear that the parentheses of this phone number do not appear in pairs, so it is not a correct phone number format.) This is the time to embed the conditions. According to the syntax above, we can get the following expressions
(\ ()? \d{3} (? ( 1) |) |-\D{3}-\D{4}
There's an important subexpression here, and we'll take it out alone to illustrate:
(? (1) \) |)
Assuming that the first subexpression (that is, the first half bracket (\)) exists, then the next half bracket should be matched, and if not the parentheses, then the "-" sign should be matched. Equivalent to an if else. Here we use pseudocode to illustrate the meaning of this expression
if (1th subexpression = = "(")
{
find ")"
}
else
{
find "-"
}
So the last expression will just match the desired result, and only the first 2 are the correct phone numbers.