"Python Core Programming" - Regular Expression Study Notes (2)

The python language supports the function of regular expressions through the re module.

The re module supports:

     (1) Multiple threads share the same compiled regular expression object.

     (2) Support named subgroups.

Common functions of the re module

1. The use of the match() function and the search() function.

Difference: The match function matches the pattern from the beginning of the string.

          The search function searches for the first occurrence of a match for a given pattern at any position.

example:

     

2. Use of group() function and groups() function.

Difference: The group() function returns the entire match object or returns a specific subgroup.

           The groups() function returns a tuple containing the subgroups.

example:

  

 

3. Use of findall() and finditer() functions.

findall() returns a list of all distinct occurrences of a regular expression pattern in the query string.

example:

The finditer() function is similar but more memory efficient. What is returned is an iterator.

example:

result:

4. Use of sub() and subn() functions.

Both functions are used to implement the search and replace function.

Difference: sub() only returns the replaced string. And subn() returns a tuple with the replaced string and the total number of replacements.

example:

                     

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325014397&siteId=291194637