【问题标题】:Python RegEx to find number value close to (before and/or behind) specific wordsPython RegEx 查找接近(之前和/或之后)特定单词的数值
【发布时间】:2021-07-30 18:41:00
【问题描述】:

我有一个如下所示的字符串:

“公寓自 2021 年起出租给学生。每月租金为 850 欧元。额外费用为水电费(150 欧元)。”

我正在寻找与“租金”和“欧元”非常接近(例如 20 个字符内)的数值。

我不想获得“2021”,也不想获得“150” - 我想获得“850”。

目前我正在使用此代码,但最终得到“2021”。你能帮帮我吗?

提前非常感谢! 费利克斯


txt = "The apartment is rented out to a student since 2021. The monthly rent is 850 Euro. Additional costs are utilities (150 Euro)."

txt = ("".join(txt)).strip()

m = re.search(r'(?:((?i:rent)|JNKM)[\w\€\:\(\)\.\!\?\-\\,\ ]{0,40}(\d+[\,\.]?\d*)|(?:(\d+[\,\.]?\d*)[\w\€\:\(\)\.\!\?\-\\,\ ]{0,40}((?i:rent)|JNKM)))',"".join(txt))

txtrent = m.group().replace(".","").replace(",",".")

txtrent = re.findall(r"-?\d+[\,\.]?\d*", txtrent    )

zustand = txtrent

print(zustand)```

【问题讨论】:

  • 如果必须有euro,为什么不用\b(?:(?i:rent)|JNKM)\b\D{0,40}(\d+(?:[,.]\d+)?)\D{0,40}\b(?i:Euro)\b?见demo
  • 这超出了堆栈溢出问题的范围,我认为正则表达式不是这项工作的正确工具。您能否展示更多示例,或链接您的完整数据集?

标签: python regex or-operator and-operator


【解决方案1】:

看看这个:


txt = "The apartment is rented out to a student since 2021. The monthly rent is 850 Euro. Additional costs are utilities (150 Euro)."
txt = txt.replace('.', '')

pattern = '\s'
result = re.split(pattern, txt)
txt = result[result.index('rent'): result.index('Euro')+1]
for i in txt:
    if i.isdigit():
        print(i)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多