How do Python regular expressions do string replacement instances

  • 2020-05-19 05:02:12
  • OfStack

Python regular expressions are often applied to string replacement code in use. There are many people do not know how to solve this problem, the following code tells you that the problem is extremely simple, I hope you have some results.

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


result, number = re.subn(regex, newstring, subject) 

2. Replace all matched substrings (using regular expression objects)


rereobj = re.compile(regex) 
result, number = reobj.subn(newstring, subject)

Python string split


reresult = re.split(regex, subject) 

String splitting (using regular representation objects)


rereobj = re.compile(regex) 
result = reobj.split(subject) 

Here is a list of 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" # ends with \Z at the end of the regular expression


if re.match(regex, subject): 
do_something() 
else: 
do_anotherthing() 

3. Create a match object and get the match details 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() 

Related articles: