How Python regular expressions perform string substitution instances

Source: Internet
Author: User
Python regular expressions are frequently applied to string substitution code in use. A lot of people do not know how to solve this problem, the following code tells you that the problem is extremely simple, I hope you have something to gain.

1. Replace all matched substrings with newstring to replace all substrings in the subject that match the regular expression regex

result, Number = RE.SUBN (regex, newstring, subject)

2. Replace all matching substrings (using regular Expression objects)

Rereobj = Re.compile (regex) result, Number = REOBJ.SUBN (newstring, subject)

Python string splitting

Reresult = Re.split (regex, subject)

String splitting (using regular expression objects)

Rereobj = Re.compile (regex) result = Reobj.split (subject)

The following are some of the matching usages of Python regular expressions:

1. Test whether the regular expression matches all or part of the string Regex=ur "..." #正则表达式

If Re.search (regex, subject):d o_something () else:do_anotherthing ()

2. Test whether the regular expression matches the entire string Regex=ur "... \z" #正则表达式末尾以 \z End

If Re.match (regex, subject):d o_something () else:do_anotherthing ()

3. Create a matching object and then get the matching details through the object Regex=ur "..." #正则表达式

Match = Re.search (regex, subject) if match:# match Start:match.start () # Match End (exclusive): Match.end () # Matched text: Match.group () do_something () else:do_anotherthing ()

The above is a detailed description of the Python regular expression in string substitution. Hope that everyone's study has helped, but also hope that we support topic.alibabacloud.com.

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.