Python learning Regular Expressions in -38.python (ii)

Source: Internet
Author: User

In Python, regular expressions also have features that are more distinctive than other programming languages. That is to support loose regular expressions.

In some cases, the regular expression will be written very long, at this time, maintenance is a problem. and the loose regular expression is the solution to this problem.

Use the last grouped code as an example:

1 ImportRe2Userinput = input ("Please input test string:")3m = Re.match (r'(\d{3,4})-(\d{8})', Userinput)4 ifm:5     Print('Area code:'+ M.group (1))6     Print('Number:'+ M.group (2))7 Else:8     Print('Format Error')

Now let's say we've been writing this code for a long time and don't know the meaning of \d{3,4} and \d{8}.

It's good to write a note at the beginning, but we can't write it.

1 # \d{3,4} represents the area code, \D{8} represents the number

Such a comment. Don ' t repeat youself. The loose regular expression is used.

1 ImportRe2Userinput = input ("Please input test string:")3Regex = R" "4    (5 \d{3,4} # area code6    )7 -# The delimiter between the area code and the number8    (9 \d{8} # numberTen    ) One " " Am =Re.match (regex,userinput,re. VERBOSE) - ifm: -     Print('Area code:'+ M.group (1)) the     Print('Number:'+ M.group (2)) - Else: -     Print('Format Error')

"represents multiple lines of text (and can also be used as a representation of document annotations).

It is worth noting that there are now a lot more whitespace in the string and comments (although they are now compiled as part of the string), but the effect is consistent.

It is also important to note that at the end of the Re.match method, the Re.verbose parameter is used, which indicates that the current regular expression is a loose regular expression. In Re.split and other methods, you need to use this parameter if you need to use a loose regular expression.

Python learning Regular Expressions in -38.python (ii)

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.