我正在使用此 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]$
丑陋的,不是吗? ;)
最佳答案
你可以像这样使用交替:
(?: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
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)))
关于python - 正则表达式匹配另一个特定术语之前或之后的术语,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36765917/