Python正则学习

.

search:寻找string中的第一个pattern

1
2
3
4
5
6
7
8
9
10
In [1]: import re
In [2]: a = "is"
In [3]: b = "This is a string for test"
In [4]: re.search(a, b)
Out[4]: <re.Match object; span=(2, 4), match='is'>
In [5]: match = re.search(a, b)
In [6]: match.start()
Out[6]: 2
In [7]: match.end()
Out[7]: 4

findall:找到所有的符合的

1
2
In [8]: re.findall(a, b)
Out[8]: ['is', 'is']

finditer:返回迭代器

1
2
3
4
5
6
In [9]: re.finditer(a, b)
Out[9]: <callable_iterator at 0x1d2e0145310>
In [10]: for i in re.finditer(a, b):
...: print(i)
<re.Match object; span=(2, 4), match='is'>
<re.Match object; span=(5, 7), match='is'>

match:只能匹配开头符合的

fullmatch:要求整个字符串都与模式匹配

标志 作用
IGNORECASE 使匹配不区分大小写
MULTILINE 使匹配可以匹配多行
DOTALL 使.可以匹配换行符
ASCII 匹配ASCII码而不是UNICODE

嵌入标志

在表达式前用(?i)来嵌入

标志 缩写
ASCII a
IGNORECASE i
MUTILINE m
DOTALL s
VERBOSE x

组命名

(?P)

组引用

(?P=name)

不同选择模式

?(id)yes_pattern|no_pattern

id是组号或编号

sub替换

subn替换并返回替换次数