Detailed Explanation of Examples of python Regular Expression Finding and Replacing Contents

  • 2021-12-05 06:44:46
  • OfStack

1. Write the Python regular expression string s.

2. Use re. compile to compile the regular expression into the regular object Patternp.

3. The regular object p calls p. search or p. findall or p. finditer to find the content.

4. The regular object p calls p. sub or p. subn to replace the content.

Instances


import re
 
s = " Regular expression "
p = re.compile(s)
 
#  Find 
mf1 = p.search(" Detection content ")
mf2 = p.findall(" Detection content ")
mf3 = p.finditer(" Detection content ")
 
#  Replace 
ms = p.sub(" Detection content ")
ms2 = p.subn(" Detection content ")
 
#  Segmentation 
mp = p.split(" Detection content ")

Content extension:

Common Rules of Regular Expressions

^ Match the beginning of a string, specifying what the string must begin with
Matches the end of a string, specifying that the string ends with the character before
+ Match the preceding character 1 or more times > = 1
{m} Specifies the number of times a character matches
? Match the preceding character 0 times or 1 time

Regular expressions are processed through the re module in python. The common methods of re module are as follows:

re. match (re rule, string, modifier): Match from scratch. The match starts with the first character of the string. If the first character does not match the rule, the match fails.

re. search (re rule, string, modifier): Match contains. Match is not required from the first character of the string. As long as there are strings that match this rule, the match is successful.

re. findall (re rule, string, modifier): Places all matching characters in a list and returns them.

re. sub (re rule, replacement string, replaced string, number of replacements, modifiers): Match characters and replace them.


Related articles: