Featured image of post Python正则表达式

Python正则表达式

知识点一:正则表达式使用方式

1
2
3
4
5
6
7

>>> import re
>>> m = re.search('(?<=abc)def', 'abcdef')
>>> m.group()
'def'
>>> m.group(0)
'def'

(?<=abc)def ,并不是从a开始搜索,而是从d往回看的

1
2
3
4
5

>>> m = re.search('(?<=-)\w+', 'email-address')
>>> m.group(0)
'address'
>>>

这个例子搜索一个跟随在连字符(-)后的单词

具体的正则使用方式可以参考官网:https://docs.python.org/zh-cn/3/library/re.html

知识点二:正则表达式对象

将正则表达式的样式编译为一个正则表达式对象,可以让程序更加高效

1
2
3

prog = re.compile(pattern)
results = prog.match(string)

等价于

1
2

result = re.match(pattern, string)

知识点三:search() vs. match()

re.search()检查字符串的任意位置,re.match()检查字符串开头

1
2
3
4
5

>>> re.match("c", "abcded") # no match
>>> re.search("c", "abcdef") # match
<re.Match object; span=(2, 3), match='c'>
>>>

search()中,可以使用^作为开始来限制匹配到字符串的首位

1
2
3
4
5
6

>>> re.match("c", "abcdef") # no match
>>> re.search("^c", "abcdef") # no match
>>> re.search("^a", "abcdef") # match
<re.Match object; span=(0, 1), match='a'>
>>>
Licensed under CC BY-NC-SA 4.0
最后更新于 Jul 30, 2025 09:56 +0800