正则表达式:匹配多个单词,但在 | 之前不匹配在 |在

Regex: match multiple words but nothing before of | at | in

我正在尝试识别字符串中的道路名称以进行跨度标记。字符串中可以有多个道路名称,但通常只有一个。

大多数道路的格式类似于

"flat 14, 24-34 barrington street, London"

"23 the honourable lord barrington's street, London"

"23 the honourable lord barrington's street, 42 the dishonarable baron lordington's street, London"

这些可以使用 (?<=\s)([a-z'\s])+(street)([a-z']+(\s)?)+(street)(?=,)

形式的基本正则表达式轻松捕获

但是有时地址的形式是

"land to the south of barrington street, London"

"plot 12 on barrington street, London"

有几个关键词几乎总是在这种情况下使用,这些词是'at'、'on'、'in'、'adjoining'.

我想制作一个正则表达式,可以匹配多个单词后跟 'street' 但不会匹配句子中的任何关键词或它之前的单词。换句话说,将提取街道名称而不是“plot 12 on”。

我曾尝试使用负面回溯,但没有成功使其发挥作用。我看过这个 answer 但它似乎不适合我使用。

您可以使用:

(?<!\S)(?:(?!\b(?:at|on|in|adjoining)\b)[^\n\d])*? street\b

模式匹配:

  • (?<!\S) 断言左侧空白边界
  • (?:非捕获组
    • (?!\b(?:at|on|in|adjoining)\b) 否定前瞻,断言不是直接在右边的任何单词
    • [^\n\d] 匹配除数字或换行符以外的任何字符
  • )*? 关闭非捕获组并选择尽可能少地重复
  • street\b 按字面匹配后跟单词边界以防止部分匹配

看到一个Regex demo and a Python demo

示例代码

import re

pattern = r"(?<!\S)(?:(?!\b(?:at|on|in|adjoining)\b)[^\n\d])*? street\b"

s = ("flat 14, 24-34 barrington street, London\n"
            "23 the honourable lord barrington's street, London\n"
            "23 the honourable lord barrington's street, 42 the dishonarable baron lordington's street, London\n"
            "land to the south of barrington street, London\n"
            "plot 12 on barrington street, London")

print(re.findall(pattern, s))

输出

[
'barrington street',
"the honourable lord barrington's street",
"the honourable lord barrington's street",
"the dishonarable baron lordington's street",
'land to the south of barrington street',
'barrington street'
]