Common examples of python re modules

  • 2021-09-11 20:52:00
  • OfStack

When we use re module, according to different use requirements, we have to choose different functions to match. Considering that everyone is a beginner of python, this site recommends common methods as the main learning goal. This article brings two functions, re. sub and re. compile. The following two parts are explained respectively, and the specific contents are as follows.

1. re. sub

re. sub is used to replace matches in a string. The following example replaces the space ''in the string with '-':


import re 

text = "JGood is a handsome boy, he is cool, clever, and so on..." 
print re.sub(r'/s+', '-', text)

import re text = "JGood is a handsome boy, he is cool, clever, and so on..." print re.sub(r'/s+', '-', text)

The function prototype of re. sub is: re. sub (pattern, repl, string, count)

The second function is the replaced string; In this case, '-'

The fourth parameter refers to the number of replacements. The default is 0, which means that every match is replaced.

re. sub also allows for complex processing of matching substitutions using functions. For example: re. sub (r '/s', lambda m: '[' + m. group (0) + ']', text, 0); Replace the space ''in the string with '[]'.

2. re. compile

You can compile a regular expression into a regular expression object. You can compile regular expressions that are often used into regular expression objects, which can improve the efficiency of 1. Here is an example of a regular expression object:


import re  

text = "JGood is a handsome boy, he is cool, clever, and so on..." 

regex = re.compile(r'/w*oo/w*') 

print regex.findall(text)  # Find all containing 'oo' Words of  

print regex.sub(lambda m: '[' + m.group(0) + ']', text) # Contains a string containing 'oo' Words used in [] Close it up. 

ES55en ES56en ES57en = "ES58en ES59en ES60en ES61en ES62en, ES63en ES64en ES65en, ES66en, ES67en ES68en ES69en..." ES70en = ES71en. ES72en (ES73en '/ES74en *ES75en/ES76en *') ES77en ES78en. ES79en (ES80en) # Find all words that contain 'ES81en' ES82en ES83en. ES84en (ES85en ES86en: '[' + ES87en. ']', text) # Enclose the words in the string that contain 'oo' with [].


Related articles: