当具体调用函数re.match 时,^ 字符确实没有什么意义,因为该函数在行首开始匹配过程。但是,对于 re 模块中的其他函数,以及在 已编译 正则表达式对象上调用 match 时,它确实有意义。
例如:
text = """\
Mares eat oats
and does eat oats
"""
print re.findall('^(\w+)', text, re.MULTILINE)
打印出来:
['Mares', 'and']
启用re.findall() 和re.MULTILINE 后,它会在文本的每一行为您提供第一个单词(没有前导空格)。
如果做一些更复杂的事情,比如用正则表达式进行词法分析,并将它应该开始匹配的文本中的起始位置传递给编译的正则表达式,它可能会很有用(您可以选择从上一场比赛)。请参阅RegexObject.match 方法的文档。
以简单的词法分析器/扫描器为例:
text = """\
Mares eat oats
and does eat oats
"""
pattern = r"""
(?P<firstword>^\w+)
|(?P<lastword>\w+$)
|(?P<word>\w+)
|(?P<whitespace>\s+)
|(?P<other>.)
"""
rx = re.compile(pattern, re.MULTILINE | re.VERBOSE)
def scan(text):
pos = 0
m = rx.match(text, pos)
while m:
toktype = m.lastgroup
tokvalue = m.group(toktype)
pos = m.end()
yield toktype, tokvalue
m = rx.match(text, pos)
for tok in scan(text):
print tok
打印出来的
('firstword', 'Mares')
('whitespace', ' ')
('word', 'eat')
('whitespace', ' ')
('lastword', 'oats')
('whitespace', '\n')
('firstword', 'and')
('whitespace', ' ')
('word', 'does')
('whitespace', ' ')
('word', 'eat')
('whitespace', ' ')
('lastword', 'oats')
('whitespace', '\n')
这区分了单词的类型;行首的单词,行尾的单词,以及任何其他单词。