Home > Backend Development > Python Tutorial > Example of how to perform string replacement using Python regular expressions

Example of how to perform string replacement using Python regular expressions

高洛峰
Release: 2017-01-12 15:37:21
Original
1767 people have browsed 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 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 objects)

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 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!

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