正则表达式是使用形式语法描述的文本匹配模板。模板被解释为一组指令,然后使用字符串作为输入执行以产生匹配的子集或原始版本的修改版本。“正则表达式”通常缩写为"regex"或“"regexp"。表达式可以包括文字匹配,重复,模板组成,分支和其他复杂的规则。与创建专用的词法分析器和解析器相比,使用正则表达式更容易解决大量的文本解析问题。Python的 re 正则表达式标准库是Python中处理不规范字符串的利器,让我们来从头学习一下Python的正则表达式吧!
最常见的用途re是搜索文本中的模板。该search()函数接受要扫描的模板和文本,并Match在找到模板时返回一个对象。如果找不到该模板,则search()返回None。每个Match对象都包含有关匹配的信息,包括原始输入字符串,使用的正则表达式以及模板中原始字符串在原有字符串中的位置。
import re
pattern = 'this'
text = 'Does this text match the pattern?'
match = re.search(pattern, text)
s = match.start()
e = match.end()
print('Found "{}"\nin "{}"\nfrom {} to {} ("{}")'.format(
match.re.pattern, match.string, s, e, text[s:e]))
输出:
Found "this"
in "Does this text match the pattern?"
from 5 to 9 ("this")
尽管re包括用于将正则表达式用作文本字符串的模块级函数,但是编译程序经常使用的表达式更为有效。该compile()函数将表达式字符串转换为RegexObject。
import re
# 编译表达式
regexes = [
re.compile(p)
for p in ['this', 'that']
]
text = 'Does this text match the pattern?'
print('Text: {!r}\n'.format(text))
for regex in regexes:
print('Seeking "{}" ->'.format(regex.pattern),
end=' ')
if regex.search(text):
print('match!')
else:
print('no match')
输出:
Text: 'Does this text match the pattern?'
Seeking "this" -> match!
Seeking "that" -> no match
search()查找文字文本字符串的单个实例。该findall() 函数返回输入的所有与模板匹配的子字符串,而不重复。
import re
text = 'abbaaabbbbaaaaa'
pattern = 'ab'
for match in re.findall(pattern, text):
print('Found {!r}'.format(match))
输出:
Found 'ab'
Found 'ab'
finditer()函数返回一个迭代器,该迭代器生成Match 实例,而不是由返回的字符串findall().
import re
text = 'abbaaabbbbaaaaa'
pattern = 'ab'
for match in re.finditer(pattern, text):
s = match.start()
e = match.end()
print('Found {!r} at {:d}:{:d}'.format(
text[s:e], s, e))
输出:
Found 'ab' at 0:2
Found 'ab' at 5:7
正则表达式比简单的文字字符串支持更强大的模板。模板可以重复,可以固定在输入中的不同逻辑位置,并且可以紧凑的形式表示,不需要在模式中出现每个文字字符。所有这些功能都通过将文字文本值与元字符结合使用,而元字符是由实现的正则表达式模式语法的一部分re。
import re
def test_patterns(text, patterns):
"""Given source text and a list of patterns, look for
matches for each pattern within the text and print
them to stdout.
"""
# Look for each pattern in the text and print the results
for pattern, desc in patterns:
print("'{}' ({})\n".format(pattern, desc))
print(" '{}'".format(text))
for match in re.finditer(pattern, text):
s = match.start()
e = match.end()
substr = text[s:e]
n_backslashes = text[:s].count('\\')
prefix = '.' * (s + n_backslashes)
print(" {}'{}'".format(prefix, substr))
print()
return
if __name__ == '__main__':
test_patterns('abbaaabbbbaaaaa',
[('ab', "'a' followed by 'b'"),
])
输出:
'ab' ('a' followed by 'b')
'abbaaabbbbaaaaa'
'ab'
.....'ab'
今天和大家一起学习了Python中的标准库 re 正则表达式 上篇,大家都学会了吗?欢迎大家关注,一起学习Python吧!
联系客服