Python RegEx to find number value close to (before and/or behind) specific words

100 views Asked by At

i have a string that looks like this:

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

I am looking to find the numeric value, which is in close proximity (within e.g. 20 chars) to "rent" and to "Euro".

I dont want to get "2021" and I dont want to get "150" - I want to get "850".

Currently I am using this code but with this I end up with "2021". Can you help me?

Thanks a lot in advance! Felix


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)```

1

There are 1 answers

0
Asir Shahriar Roudra On

check this out:


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)