Python regular expressions classic introduction tutorial

  • 2020-06-01 10:11:50
  • OfStack

This example summarizes the basic use of Python regular expressions. I will share it with you for your reference as follows:

Regular expressions are often used for text processing (the crawler parses the fields in html and grabs some key data when analyzing the log file). In general, we will use Python's re library. If the regular expression is used repeatedly in its own code, we can convert the regular expression to one object for easy invocation using the re.compile function.


Matches the input string from the first character and returns null if it does not match.


Unlike match, search is free to start matching at any position in the string until it matches.

Options in re

Usually you can set it in flag.

re.I Ignore case
re.L Let \w,\W,\b,\B,\s and \S do localization
re.M Multiple line matching is supported when matching.
re.DEBUG Displays debugging information for regular expressions
re.S Let the. Sign match all the characters on the line.

sub replacement

import re
phone='188-88-88 # this is my phone number'
num = re.sub(r'#.*$','',phone)
# num ==188-88-88
num = re.sub(r'\D','',phone)
# num = 1888888

You can also use this to escape code, kind of like the lookup substitution used in sublime text. Let's say I need to convert the macro definition in C to the variable definition in lua

import re
print( re.sub( r'#define\s+([a-zA-Z_]+)\s+([a-zA-Z_0-9]+)', r'_G.\1 = \2', '#define MAX_RECV_SIZE 100' ) )

The subn function is similar, but the number of substitutions can be customized.


Return the matched contents into an array, which should be a common method.

print( re.findall( '\d+', '66,88,88,777' ) )
# ['66', '88', '88', '777']


The matched content is returned as an iterator, and we can loop through this, MatchObject when we return

for num in re.finditer( '\d+', '66,88,88,777' ):


re.split(pattern, string, maxsplit=0, flags=0) 
>>> re.split(',', 'Words, words, words.')
['Words', ' words', ' words.']
>>> re.split('\W+', 'Words, words, words.')
['Words', 'words', 'words', '']
>>> re.split('(\W+)', 'Words, words, words.')
['Words', ', ', 'words', ', ', 'words', '.', '']

The uppercase \W represents a non-string, which can be found in the syntax. If parentheses are added, the split string that matches will not be omitted. And the last one that's in the array as a string separator, is left in the array.


This function is an auxiliary function, when writing a large number of regular expressions, maybe we fixed some string contains the regular reserved string, but we do not need to let the program when it is an re expression, can use this function to do the string conversion.

# result

Note grammar:

模式 描述
^ 匹配字符串的开头
$ 匹配字符串的末尾。
. 匹配任意字符,除了换行符,当re.DOTALL标记被指定时,则可以匹配包括换行符的任意字符。
[…] 用来表示1组字符,单独列出:[amk] 匹配 ‘a','m'或'k'
[^…] 不在[]中的字符:[^abc] 匹配除了a,b,c之外的字符。
re* 匹配0个或多个的表达式。
re+ 匹配1个或多个的表达式。
re? 匹配0个或1个由前面的正则表达式定义的片段,非贪婪方式re{ n}
re{ n,} 精确匹配n个前面表达式。
re{ n, m} 匹配 n 到 m 次由前面的正则表达式定义的片段,贪婪方式a
(re) G匹配括号内的表达式,也表示1个组
(?imx) 正则表达式包含3种可选标志:i, m, 或 x 。只影响括号中的区域。
(?-imx) 正则表达式关闭 i, m, 或 x 可选标志。只影响括号中的区域。
(?: re) 类似 (…), 但是不表示1个组
(?imx: re) 在括号中使用i, m, 或 x 可选标志
(?-imx: re) 在括号中不使用i, m, 或 x 可选标志
(?#…) 注释.
(?= re) 前向肯定界定符。如果所含正则表达式,以 … 表示,在当前位置成功匹配时成功,否则失败。但1旦所含表达式已经尝试,匹配引擎根本没有提高;模式的剩余部分还要尝试界定符的右边。
(?! re) 前向否定界定符。与肯定界定符相反;当所含表达式不能在字符串当前位置匹配时成功
(?> re) 匹配的独立模式,省去回溯。
\w 匹配字母数字
\W 匹配非字母数字
\s 匹配任意空白字符,等价于 [\t\n\r\f].
\S 匹配任意非空字符
\d 匹配任意数字,等价于 [0-9].
\D 匹配任意非数字
\A 匹配字符串开始
\Z 匹配字符串结束,如果是存在换行,只匹配到换行前的结束字符串。c
\z 匹配字符串结束
\G 匹配最后匹配完成的位置。
\b 匹配1个单词边界,也就是指单词和空格间的位置。例如, ‘er\b' 可以匹配”never” 中的 ‘er',但不能匹配 “verb” 中的 ‘er'。
\B 匹配非单词边界。'er\B' 能匹配 “verb” 中的 ‘er',但不能匹配 “never” 中的 ‘er'。
\n, \t, 等. 匹配1个换行符。匹配1个制表符。等
\1…\9 匹配第n个分组的子表达式。
\10 匹配第n个分组的子表达式,如果它经匹配。否则指的是8进制字符码的表达式。

PS: here are 2 more convenient regular expression tools for your reference:

JavaScript regular expression online testing tool:

Online regular expression generation tool:

More about Python related content to view this site project: the Python regular expression usage summary ", "Python data structure and algorithm tutorial", "Python Socket programming skills summary", "Python function using techniques", "Python string skills summary", "Python introduction and advanced tutorial" and "Python file and directory skills summary"

I hope this article is helpful for you to design Python program.

Related articles: