How to replace strings with Python Regular Expressions

Source: Internet
Author: User

Python regular expressions are often used to replace strings. Many people do not know how to solve this problem. The code below tells you that the problem is extremely simple and I hope you will gain some benefits.

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

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

2. replace all matched substrings with regular expression objects)

 
 
  1. Rereobj = re. compile (regex)
  2. Result, number = reobj. subn (newstring, subject) string split

Python string splitting

 
 
  1. reresult = re.split(regex, subject) 

String sharding uses regular expression objects)

 
 
  1. Rereobj = re. compile (regex)
  2. Result = reobj. split (subject) Match

The following lists the matching usage of Python Regular Expressions:

1. test whether the regular expression matches all or part of the string regex = ur "..." # Regular Expression

 
 
  1. if re.search(regex, subject):  
  2. do_something() 

Else: do_anotherthing () 2. test whether the regular expression matches the entire string regex = ur "... \ Z" # End with \ Z at the end of the regular expression

 
 
  1. if re.match(regex, subject):  
  2. do_something()  
  3. else:  
  4. do_anotherthing() 

3. Create a matching object and obtain the matching details through this object. regex = ur "..." # Regular Expression

 
 
  1. match = re.search(regex, subject)  
  2. if match:  
  3. # match start: match.start()  
  4. # match end (exclusive): match.end()  
  5. # matched text: match.group()  
  6. do_something()  
  7. else:  
  8. do_anotherthing() 

The above is a detailed description of the Python Regular Expression in string replacement.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.