正则表达式函数(一)
- 模块
- 函数或方法
- 1. 基于模块 *==re==* 的正则表达式编译方法
- 2. 基于模块 ==*re*== 的匹配操作方法
- 2.1 re.search(pattern, string, flags=0)
- 2.2 re.match(pattern, string, flags=0)
- 2.3 re.fullmatch(pattern, string, flags=0)
- 2.4 re.split(pattern, string, maxsplit=0, flags=0)
- 2.5 re.findall(pattern, string, flags=0) / re.finditer
- 2.6 re.sub(pattern, repl, string, count=0, flags=0)
- 2.7 re.subn(pattern, repl, string, count=0, flags=0)
- 2.8 re.purge()
模块
首先,导入模块
import re
函数或方法
1. 基于模块 re 的正则表达式编译方法
- 函数原型:re.compile(pattern, flags=0)
- 编译正则表达式字符串为正则表达式对象,被用于 match() 和 search() 函数
- flags 用于指定正则表达式的模式,各个模式之间可以使用 OR 或 | 串联
常见的 flags 如下:
flag | 含义 |
---|---|
re.A re.ASCII | 仅匹配 ASCII 字符 |
re.DEBUG | 显示 DEBUG 信息 |
re.I re.IGNORECASE | 忽略大小写 |
re.M re.MULTILINE | 若被指定时,模式字符 ^ 仅匹配每行的开头(紧随每个换行符之后)匹配;模式字符 $ 仅匹配每行的末尾(紧接在每个换行符之前)匹配。而在 默认情况下,^ 仅在字符串的开头匹配,$ 仅在字符串的末尾匹配 |
re.S re.DOTALL | 若被指定, . 特殊字符完全可以与任何字符匹配,包括换行符;若未指定,. 将匹配换行符以外的任何字符 |
re.X re.VERBOSE | 以用户友好的方式进行展现,即允许换行编写正则表达式,也可添加注释信息 |
prog = re.compile(pattern)
result = prog.match(string)
等同于
result = re.match(pattern, string)
re.X 例子:
a = re.compile(r"""\d + # the integral part
\. # the decimal point
\d * # some fractional digits""", re.X)
b = re.compile(r"\d+\.\d*")
2. 基于模块 re 的匹配操作方法
2.1 re.search(pattern, string, flags=0)
- 基于整个字符串范围的搜索匹配子串 substring,仅返回第一个匹配对象
- 如果没有匹配到,则返回 None
In [2]: string = "The 1896 Cedar Keys hurricane was a powerful tropical cyclone that devastated much of the East Coast of the United States, starting with Florida's Cedar Keys, near the end of September."
In [16]: p = re.compile(r"(st\w+\b)", re.I)
In [17]: m = re.search(p, string)
In [18]: m.group()
Out[18]: 'stated'
2.2 re.match(pattern, string, flags=0)
- 仅从字符串的开始位置执行匹配,且仅返回第一个匹配对象
- 若果没有匹配到,则返回 None
In [23]: s1 = re.compile(r"Cedar", re.I)
In [24]: m1 = re.match(s1, string)
In [25]: m1 == None
Out[25]: True
In [26]: s2 = re.compile(r"The", re.I)
In [27]: m2 = re.match(s2, string)
In [28]: m2 == None
Out[28]: False
In [29]: m2.group()
Out[29]: 'The'
2.3 re.fullmatch(pattern, string, flags=0)
- 基于整个 string 匹配正则表达式,返回一个匹配对象
- 如果没有匹配成功,则返回 None
In [26]: s2 = re.compile(r"The", re.I)
In [32]: m3 = re.fullmatch(s2, string)
In [33]: m3 == None
Out[33]: True
In [34]: fullstr = "The"
In [35]: m3 = re.fullmatch(s2, fullstr)
In [36]: m3 == None
Out[36]: False
2.4 re.split(pattern, string, maxsplit=0, flags=0)
- 在模式匹配发生的位置,分隔字符串,并返回分隔后各元素组成的列表。结果列表中不包含 pattern 匹配的 substr
- 如果在正则表达式中,引入了捕获分组(圆括号),结果列表中包含 pattern 匹配的 substr
- 如果指定 maxsplit ,则分隔次数为 maxsplit,并返回分割后的结果列表
In [37]: re.split(r'\W+', 'Words, words, words.')
Out[37]: ['Words', 'words', 'words', ''] # 最后有一个空白字符
In [38]: re.split(r'(\W+)', 'Words, words, words.')
Out[38]: ['Words', ', ', 'words', ', ', 'words', '.', '']
In [39]: re.split(r'\W+', 'Words, words, words.', 1)
Out[39]: ['Words', 'words, words.']
In [40]: re.split('[a-f]+', '0a3B9', flags=re.IGNORECASE)
Out[40]: ['0', '3', '9']
- 在捕获分组过程中,如果 pattern 匹配了开头,则在返回列表中包含一个空字符串
In [2]: re.split(r'(\W+)', '...words, words...')
Out[2]: ['', '...', 'words', ', ', 'words', '...', '']
2.5 re.findall(pattern, string, flags=0) / re.finditer
- 返回所有 pattern 匹配的内容(从左到右),并保存在一个列表对象中
- 如果 pattern 含有捕获组,则返回一个元组列表
- 有时结果中包含空匹配结果
In [7]: re.findall(r'(\w{5})([0-9]+)', 'words2009, words2010, words2011')
Out[7]: [('words', '2009'), ('words', '2010'), ('words', '2011')]
text = "He was carefully disguised but captured quickly by police."
for m in re.finditer(r"\w+ly", text):
print('%02d-%02d: %s' % (m.start(), m.end(), m.group(0)))
Out:07-16: carefully
Out: 40-47: quickly
2.6 re.sub(pattern, repl, string, count=0, flags=0)
- 返回 repl 替换 pattern 匹配内容的 string
- 如果 pattern 没有匹配,则返回未变化的 string
- repl 可以是一个字符串,也可以是一个函数
- 如果 repl 是字符串,则 \ 是一个转义字符,即 \n 表示换行符,etc。
- 如果 repl 是一个函数,则 pattern 匹配的内容是函数的参数
- count 表示最大替换次数,如果是 0 或者不提供,则全部进行替换
# repl -> string
In [10]: re.sub(r'def\s+([a-zA-Z_][a-zA-Z_0-9]*)\s*\(\s*\):',
...: r'static PyObject*\npy_\1(void)\n{',
...: 'def myfunc():')
Out[10]: 'static PyObject*\npy_myfunc(void)\n{'
# repl -> function
In [14]: def dashrepl(matchobj):
...: if matchobj.group(0) == '-': return ' '
...: else: return '-'
In [15]: re.sub('-{1,2}', dashrepl, 'pro----gram-files')
Out[15]: 'pro--gram files'
In [16]: re.sub(r'\sAND\s', ' & ', 'Baked beans And Spam', flags = re.IGNORECASE
Out[16]: 'Baked beans & Spam'
特例1 :空匹配替换
In [17]: re.sub('x*', '-', 'asdxd')
Out[17]: '-a-s-d--d-'
In [18]: re.sub('.*', '-', 'asdxd')
Out[18]: '--'
In [19]: re.sub('\W*', '-', 'asdxd')
Out[19]: '-a-s-d-x-d-'
特例2 :使用捕获子组语法
- 有两种形式使用捕获子组
- \g<number> 表示捕获的第 number 组,当为 0 时,表示所有匹配;1 表示第一个子组
- pattern 是 (?P<name>…) 正则表达式时,可以采用 \g<name> 替换子组
[24]: re.sub(r'\s(AND)\s', ' &(\g<1>) ', 'Baked beans And Spam', flags = re.IGNORECASE)
Out[24]: 'Baked beans &(And) Spam'
2.7 re.subn(pattern, repl, string, count=0, flags=0)
- 同 re.sub ,但是返回 (new_string, number_of_subs_made)。
2.8 re.purge()
- 清楚正则表达式缓存