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.