模块
- python 处理正则表达式的模块是 re
import re
匹配
match(pattern, string, flags=0)
用来判断pattern
是否匹配string
,如果匹配,返回的是一个 match
对象,如果不匹配,返回 None
。在 pattern
中可以通过 \num
或者 (?P=group)
引用分组。
Match
对象主要有三个方法:
方法 | 作用 |
---|---|
group(num=0) | 返回匹配内容,如果num为0,返回整个匹配内容,否则返回相应匹配的分组 |
groups(default=None) | 以tuple的形式返回所有匹配的子组 |
groupdict(default=None) | 以dict的形式返回所有匹配的子组 |
注:所谓子组,是指正则表达式中用小括号括起来的分组,子组的顺序按照左小括号的顺序来决定。
例子:
#coding=utf-8
import re
PATTERN = r'(?P<prefix>\d{3})-?(?P<number>\d{8})'
PHONE_NUMBER = '18612345678'
m = re.match(PATTERN, PHONE_NUMBER)
if m is not None:
print(m.group()) # 18612345678
print(m.group(0)) # 18612345678
print(m.group(1)) # 186
print(m.group(2)) # 12345678
print(m.groups()) # ('186', '12345678')
print(m.groupdict()) # {'prefix': '186', 'number': '12345678'}
else:
print("Does not match")
搜索
search(pattern, string, flags=0)
用来在 string
中搜索第一次 pattern
匹配的地方。如果找到,返回 match
对象,否则返回 None
:
例子:
#coding=utf-8
import re
PATTERN = r'12345'
TEST_STR = '1112345'
m = re.search(PATTERN, TEST_STR)
if m is not None:
print(m.group()) # 12345
else:
print("Does not match")
查找
findall(pattern, string[,flags])
查找 string
中出现的所有 pattern
,返回匹配列表。
finditer(pattern, string[, flags])
与 findall
类似,不同的是返回迭代器。
例子:
#coding=utf-8
import re
PATTERN = r'\d{3}'
TEST_STR = '123456789'
print(re.findall(PATTERN, TEST_STR)[0]) # ['123', '456', '789']
print([m.group() for m in re.finditer(PATTERN, TEST_STR)]) # ['123', '456', '789']
替换
sub(pattern, repl, string, count=0)
将 string
中的 pattern
替换为 repl
,count
表示替换的次数。在 repl
中可以通过 \num
或者 \g<groupname>
来引用 pattern
中的分组。
例子:
#coding=utf-8
import re
PATTERN = r'(\w)\1' # 或者 r'(?P<coupled>\w)(?P=coupled)'
REPL = r'\1\1\1' # 或者 r'\g<coupled>\g<coupled>\g<coupled>'
TEST_STR = 'A good cook could cook as much cookies as a good cook who could cook cookies.'
print(re.sub(PATTERN, REPL, TEST_STR))
# A goood coook could coook as much coookies as a goood coook who could coook coookies.
分割
split(pattern, string, max=0)
将 string
按照 pattern
分割,最多 max
次。
例子:
#coding=utf-8
import re
PATTERN = r'\s'
TEST_STR = '123 456\t\t789\n'
print(re.split(PATTERN, TEST_STR))
# ['123', '', '', '', '456', '', '789', '']
# remove blank using filter()
print([item for item in filter(lambda x: x!='', re.split(PATTERN, TEST_STR))])
# ['123', '456', '789']
标志
标志 | 作用 |
---|---|
re.I , re.IGNORECASE | 忽略大小写 |
re.L , re.LOCALE | \w, \W, \b, \B, \s, \S 本地化 |
re.M , re.MULTILINE | ^$匹配每一行,而不是整个字符串 |
re.S , re.DOTALL | .也匹配\n |
re.X , re.VERBOSE | 忽略空格和空格后面的#号,多用在注释 |