Skip to main content
 首页 » 编程设计

python之正则表达式 match() 无法捕获 python 中的简单模式

2024年08月27日28linjiqin

我正在尝试在 Python 中使用一些简单的正则表达式函数。我正在使用正则表达式来捕捉阿拉伯字母表中的模式,但在最简单的情况下,当一个人在模式的开头添加几个字母时,无论是否有连字,它似乎都不起作用:

>>> p = re.compile(r'ترينهايمان') 
>>> p.match('به ترينهايمان') 
>>> 
 
 
>>> p = re.compile(r'ترینهایمان') 
>>> p.match('بهترینهایمان')  
>>> 

较长的字符串基本上是在开头添加两个字母的模式本身。

据我所知,匹配应该返回一个值,但它没有。

这很奇怪,因为当你在模式的末尾添加一个字母时,它会捕捉到它:

>>> p = re.compile(r'ترينهايمان') 
>>> p.match('ترينهايماني') 
<_sre.SRE_Match object at 0x02C52FA8> 
>>> p.match('بهترينهايمان') 
>>> 

请您参考如下方法:

re.match 将只匹配从字符串开头开始的模式:

re.match(pattern, string, flags=0)

If zero or more characters at the beginning of string match the regular expression pattern, return a corresponding MatchObject instance. Return None if the string does not match the pattern; note that this is different from a zero-length match.

由于您尝试匹配开头有额外字符的字符串,match 不会将该字符串识别为匹配项。您需要改用 re.search。