Regular Expressions-embedding conditions (vii) _ Regular expressions

Source: Internet
Author: User
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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.