Python uses regular expressions to replace strings

高洛峰
Release: 2017-03-11 10:40:07
Original
3465 people have browsed it

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)
Copy after login

2. Replace all matching substrings (using regular expression object)

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

Python string splitting

reresult = re.split(regex, subject)
Copy after login

String splitting (using regular expression objects)

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

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()
Copy after login

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()
Copy after login

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()
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!