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 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 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 a detailed introduction to Python regular expressions in string replacement. I hope it will be helpful to everyone's learning, and I also hope that everyone will support the PHP Chinese website.
For more articles related to examples of how to perform string replacement with Python regular expressions, please pay attention to the PHP Chinese website!