首页 > 解决方案 > 在 python 的正则表达式中使用 lookbehnd 提取字符串直到 '\n' 字符。它也可以有字母数字字符、特殊字符和空格

问题描述

text = '我的叔叔住进了医院。\n 他已经患了 10 个月。\n 医院的地址是 \nApollo Health City Campus, Jubilee Hills, Hyderabad - 500 033。'

现在我想提取医院的地址,即' Apollo Health City Campus,Jubilee Hills, Hyderabad -**' 使用正则表达式lookbehind,我使用了以下代码,但我想要一个表达式,可以帮助我提取字符串直到 \n六位密码之前的字符,即 '500 033' 目前我正在尝试提取 6 个字符串,但我想要一个正则表达式,它可以帮助我获取所有字符串,直到 '\n' 。

r'((\w\S+\s+){1,6})(?=500 033)'

预期输出 - ' Apollo Health City Campus, Jubilee Hills, Hyderabad - '即 \n 之前的所有字符串

标签: pythonpython-3.xregexpython-2.7regex-lookarounds

解决方案


为什么不简单地使用拆分\n并获取最后一个字符串?

text = ' My uncle is admitted in the hospital.\n He has been suffering from 10 months.\n The address of the hospital is \nApollo Health City Campus, Jubilee Hills, Hyderabad - 500 033. '
print(text.split('\n')[-1])

如果您确定该字符串将包含一个密码。即6位数字,另一种方法可能是:

text = ' My uncle is admitted in the hospital.\n He has been suffering from 10 months.\n The address of the hospital is \nApollo Health City Campus, Jubilee Hills, Hyderabad - 500 033. '
for x in text.split('\n'):
    if [idx.isdigit() for idx in x].count(True)==6:
        print(x)

我只在一个字符串中添加了一个 6 位数字的检查。您可以根据自己的需要进行修改。


推荐阅读