【问题标题】:balancing reluctant and greedy matching平衡勉强匹配和贪婪匹配
【发布时间】:2016-04-14 03:54:47
【问题描述】:

我正在尝试匹配下面的两个地址行(主要是虚构地址):

2320 ZINER CIR East 43123
1111 ZINER CIR East Bernstadt 43123

我的正则表达式是使用城市名称构建的,而 East Bernstadt 是一个城市名称。然而,街道也可以以“东”结尾。我的困境是,如果我贪婪地匹配“东方”,如:

\d+ [^ ]+ CIR( East)?( East Bernstadt)?(?: \d+)?

...那么只有第一行匹配(另一行是部分匹配)。如果我使用不情愿的匹配,如:

\d+ [^ ]+ CIR( East)??( East Bernstadt)?(?: \d+)?

...第二行匹配但第一行不匹配。

如何更改正则表达式以使两行完全匹配? “East”和“East Bernstadt”必须保留在表达式的不同部分。

编辑: 我不能用一个括号组来处理“East”和“East Bernstadt”;上述两个表达式都必须匹配,但“1234 Ziner CIR East East Bernstadt”也必须匹配(某些街道上有主要方向)。

【问题讨论】:

    标签: java regex regex-greedy non-greedy


    【解决方案1】:

    试试这个

    \d+\s+\S+\s+CIR(?:(?!\sEast Bernstadt)\s+East)?(?:\s+East Bernstadt)?(?: +\d+)?
    

    Regex demo

    解释:
    \s:“空白字符”:空格、制表符、换行符、回车、垂直制表符sample
    \S:一个字符不是由\S sample
    (?!…) 定义的空白字符:负前瞻 sample

    【讨论】:

    • 谢谢,但我不能将 East 和 East Bernstadt 放在同一个表达式中,因为它们是完全不同的单位。例如,这将不匹配“1234 Ziner CIR East East Bernstadt”。有些街道的尽头有一个主要方向。我将编辑问题以添加此内容。
    • 太完美了!谢谢。
    猜你喜欢
    • 1970-01-01
    • 2017-10-16
    • 2014-07-06
    • 1970-01-01
    • 2012-06-27
    • 2015-02-11
    • 2011-08-29
    • 1970-01-01
    • 2012-11-17
    相关资源
    最近更新 更多