【问题标题】:RegEx to match a term before OR after another specific term正则表达式匹配另一个特定术语之前或之后的术语
【发布时间】:2016-04-21 09:50:40
【问题描述】:

我正在使用此 RegExpression 在某种文本中寻找平方米术语:

([0-9]{1,3}[\.|,]?[0-9]{1,2}?)\s?m\s?[qm|m\u00B2]

效果很好。

现在,只有在它之前或之后存在“Wohnfläche”/“Wohnfl”/“Wfl”之类的字符串时,才应该匹配这个东西。换句话说:后一个术语是强制性的,但它的位置不是。 为这个写一个正则表达式通常不是问题,我的问题是如何写得最优雅。目前我只看到一种方法:

^[.]*[Wohnfläche|Wohnfl|Wfl]([0-9]{1,3}[\.|,]?[0-9]{1,2}?)\s?m\s?[qm|m\u00B2]

新搜索,结合“或”语句(我使用的是 Python)

([0-9]{1,3}[\.|,]?[0-9]{1,2}?)\s?m\s?[qm|m\u00B2][.]*[Wohnfläche|Wohnfl|Wfl]$

丑陋,不是吗? ;)

【问题讨论】:

  • 请张贴输入和所需匹配的清晰示例。

标签: python regex


【解决方案1】:

你可以像这样使用交替:

(?:Wohnfläche|Wohnfl|Wfl)\s*(\d{1,3}(?:[.,]\d{1,2})?)\s?m\s?(qm|m\u00B2)|(\d{1,3}(?:[.,]\d{1,2})?)\s?m\s?(qm|m\u00B2)\s*(?:Wohnfläche|Wohnfl|Wfl)

并检查匹配的捕获组。只是不能在正则表达式的两边选择性地使用限制性字符串,只会被忽略。

regex demo

IDEONE demo:

import re
pat = re.compile(r'(?:Wohnfläche|Wohnfl|Wfl)\s*(\d{1,3}(?:[.,]\d{1,2})?)\s?m\s?(qm|m\u00B2)|(\d{1,3}(?:[.,]\d{1,2})?)\s?m\s?(qm|m\u00B2)\s*(?:Wohnfläche|Wohnfl|Wfl)')
strs = ["12,56m qm Wohnfläche", "14.54 mqm Wohnfl", "Wfl 134 m qm"]
for x in strs:
    m = pat.search(x)
    if m:
        if m.group(1): # First alternative found a match
            print("{}".format(m.group(1), " - ", m.group(2)))
        else:          # Second alternative "won"
            print("{}".format(m.group(3), " - ", m.group(4)))

【讨论】:

    【解决方案2】:

    在控制应用程序中指定一个逻辑连词,例如(伪代码)<area-regex>.match(string) and <text-regex>.match(string)

    这假设同一字符串上的两个正则表达式的任何一对匹配项永远不会重叠(如果它们重叠,你会得到一个误报)。您的正则表达式满足此要求。

    请注意,您的文本上下文的正则表达式包含附加限制,即您的测试字符串以匹配开始或结束,而在您的非正式描述中,您只需要在区域规范之前或之后发生匹配。在下面的代码中,ptpt_anchored 合并了这种差异。

    Python 片段(未经测试):

    import re
    ...
    # pa:          <area_regex>
    # pt:          <text_regex>
    # pt_anchored: <text_regex>, anchored
    #
    pa          = re.compile ( r'([0-9]{1,3}[\.|,]?[0-9]{1,2}?)\s?m\s?[qm|m\u00B2]' )
    pt          = re.compile ( r'[.]*[Wohnfläche|Wohnfl|Wfl]' )                         
    pt_anchored = re.compile ( r'^[.]*[Wohnfläche|Wohnfl|Wfl]|[.]*[Wohnfläche|Wohnfl|Wfl]$' )
    
    if pa.match(<teststring>) and pt.match(<teststring>):
        print 'Match found: '
    else:
        print 'No match'
    ...
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-18
      相关资源
      最近更新 更多