Home > Article > Backend Development > Python uses regular expressions to replace strings
Python regular expressions are often used in string replacement codes. This article mainly introduces how to perform string replacement with Python regular expressions. It has certain reference value. Interested friends can refer to it.
Python regular expressions are often used in string replacement codes. Many people don't know how to solve this problem. The following code will tell you that this problem is actually extremely simple. I hope you gain something.
1. Replace all matching substrings. Use 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 object)
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 several matching uses of Python regular expressions:
1. Test whether the regular expression matches all or part of the string regex=ur"..." #Regular expression
if re.search(regex, subject): do_something() else: do_anotherthing()
2. Test whether the regular expression matches the entire string regex=ur"...\Z" #The end of the regular expression ends with \Z
if re.match(regex, subject): do_something() else: do_anotherthing()
3 . Create a matching object, and then obtain the matching details through the object regex=ur"..." #Regular expression
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 the Python regular expression A detailed introduction of the formula in string replacement. I hope it will be helpful to everyone's learning, and I also hope that everyone will support Script Home.
The above is the detailed content of Python uses regular expressions to replace strings. For more information, please follow other related articles on the PHP Chinese website!