据我所知,match
:给定一个字符串str和一个pat模式,match从str的开始检查str是否与模式匹配。search
:给定字符串str和模式pat,search检查str是否与str的每个索引中的模式匹配。
如果是,那么在regex with match的开头使用'^'
是否有意义?
据我所知,既然match
从一开始就已经检查过了,就没有。我可能错了;我的错在哪里?
最佳答案
当具体调用函数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方法的文档。
以简单的lexer/扫描仪为例:
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')
这就区分了词的类型;一行开头的词,一行结尾的词,以及其他任何词。