Python

Python,第1张

Python

re.match
锚定在字符串的开头。这与换行无关,因此它与
^
模式中使用的方式不同。

如重新匹配文档所述:

如果字符串开头的零个或多个字符 与正则表达式模式匹配,则返回相应的

MatchObject
实例。None如果字符串与模式不匹配,则返回;否则返回
false
。请注意,这与零长度匹配不同。

注意:如果要在字符串中的任何位置找到匹配项,请

search()
改用。

re.search
搜索整个字符串,如文档所述:

扫描字符串以查找正则表达式模式产生匹配的位置,然后返回相应的

MatchObject
实例。None如果字符串中没有位置与模式匹配,则返回;否则返回
false
。请注意,这与在字符串中的某个点找到零长度匹配不同。

因此,如果你需要匹配字符串的开头,或者匹配整个字符串,请使用

match
。它更快。否则使用
search

该文档中有一个专门针对

matchvs
.的部分
search
,还涵盖了多行字符串:

python提供两种不同的基本 *** 作基于正则表达式:

match
检查是否有比赛 才刚刚开始的字符串,而
search
用于匹配检查 任何地方的字符串(这是
Perl
并默认情况下)。

请注意,

match
可以从不同的
search
使用开头的正则表达式时,即使
'^':'^'
只在字符串的开头匹配,或 MULTILINE模式换行也紧随其后。仅当模式在字符串的开头( 无论模式如何)或在可选 参数指定的开始位置匹配(无论换行符是否在其前面)时,
match
*** 作才会成功
pos

现在,足够多的谈话。现在来看一些示例代码:

# example pre:string_with_newlines = """somethingsomeotherthing"""import reprint re.match('some', string_with_newlines) # matchesprint re.match('someother',     string_with_newlines) # won't matchprint re.match('^someother', string_with_newlines,     re.MULTILINE) # also won't matchprint re.search('someother',      string_with_newlines) # finds somethingprint re.search('^someother', string_with_newlines,      re.MULTILINE) # also finds somethingm = re.compile('thing$', re.MULTILINE)print m.match(string_with_newlines) # no matchprint m.match(string_with_newlines, pos=4) # matchesprint m.search(string_with_newlines,     re.MULTILINE) # also matches


欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/4888494.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-11-12
下一篇 2022-11-12

发表评论

登录后才能评论

评论列表(0条)

保存