正则表达式搜索从左到右?

2024-04-19 06:43:32 发布

您现在位置:Python中文网/ 问答频道 /正文

>>> test1 = "123 main street, slc, utah county, utah 84115"  # test string
>>> address_end_pattern3 = re.compile(r"\b((ut(ah)?)\,?[\s\n](84\d{3}(\-\d{4})?)|(84\d{3}(\-\d{4})?)|(ut(ah)?))\b", re.IGNORECASE) # all 3 patterns concatenated with | in the order I would like it to be found
>>> address_end_pattern2 = re.compile(r"\b((ut(ah)?)\,?[\s\n](84\d{3}(\-\d{4})?)|(84\d{3}(\-\d{4})?))\b", re.IGNORECASE)  # 2 patterns omitting the state only pattern
>>> address_end_pattern1 = re.compile(r"\b(ut(ah)?)\,?[\s\n](84\d{3}(\-\d{4})?)\b", re.IGNORECASE)  # the first pattern (state and zip) alone
>>> address_end_pattern1.search(test1).group()
'utah 84115'  # it finds the first pattern correctly when it is the only pattern
>>> address_end_pattern3.search(test1).group()  # but not when the state only pattern is there
'utah'
>>> address_end_pattern2.search(test1).group()
'utah 84115'  # finds the first pattern when combined with zip alone

在前一个问题证实后,我相信regex从左到右搜索字符串和模式。。。但后来事情发生了。如果它自己正确地找到了该模式,并且在与zip模式连接时,它为什么只在连接模式中最后一个选项时才找到状态模式?有人能解释这种行为吗?在

编辑: 为了清楚起见,如果第一个模式:

^{pr2}$

我试着找出一些东西,比如: 犹他州,84115 或 犹他州,84115-0001

如果没有出现这种情况,那么我只能选择邮政编码来标识地址的结尾:

r"\b(84\d{3}(\-\d{4})?))\b"

应该与以下内容相匹配:

84115个 或 84115-0011号

最后,如果两者都不匹配,那么我只想查找状态:

\b(ut(ah)?)\b

应匹配: 美国犹他州 或 犹他州

我想按这个顺序查找,因为后两个可能会切断一些信息,或者在各种情况下使用第二个地址,因为地址列为:

SLUT大街123845号和C大街1234号


Tags: thereonlyaddress模式itendpattern
3条回答

正则表达式与utah county中的utah匹配,这是因为您在第3个模式中使用了第3个选项。因为它出现在你想要的“犹他84115”之前,这是你的第一场比赛,utah 84115是第二场比赛。如果你在“犹他84115”和“犹他县”之间切换,就可以了。https://regex101.com/r/zQ4rJ1/5。在

我不确定这是否是您想要的,但是如果您使用findall而不是search,这应该会返回一个您要查找的所有匹配项的列表。在

address_end_pattern3.findall(test1)

我不确定,但我想你的问题与re.search如何工作和{}之间的相互作用有关。在

正则表达式搜索总是在首先开始的文本中找到匹配项。对于您的示例模式,这是"utah county""utah"部分。如果模式中的多个备选方案可以从同一个字符开始匹配,那么它将选择模式中的备选方案(在|的左侧),这可能不是最长的。当使用search(而不是findall)时,文本的其余部分甚至都不会被检查,因此没有办法得到后面的匹配。在

您的示例模式和文本可以简化为一个更简单的示例,这可能有助于您处理它并了解发生了什么。这里a是“犹他”(在文本中出现两次)的替身,b是邮政编码的替代(只出现一次)。在

>>> re.search('ab|a|b', 'a ab').group()
'a'

相关问题 更多 >