简体   繁体   English

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

[英]extract strings till ' \n ' character using lookbehnd in regex in python. And it can have alphanumeric characters, special characters and space also

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. ' text = '我的叔叔住进了医院。\n 他已经患了 10 个月的病。\n 医院的地址是 \nApollo Health City Campus, Jubilee Hills, Hyderabad - 500 033。'

now i want to extract the address of the hospital ie ' Apollo Health City Campus, Jubilee Hills, Hyderabad -** ' using regex lookbehind, i used the following code but i want a expression that can help me extract the strings uptill the \n character prior to the six digit pincode ie '500 033' Currently am trying to extract 6 strings but i want a regex expression that can help me get all the strings till '\n'.现在我想提取医院的地址,即' Apollo Health City Campus,Jubilee Hills, Hyderabad -**' 使用正则表达式lookbehind,我使用了以下代码,但我想要一个表达式,可以帮助我提取字符串直到 \n六位数密码之前的字符,即'500 033' 目前我正在尝试提取6 个字符串,但我想要一个正则表达式,它可以帮助我获取所有字符串,直到'\n'。

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

expected output - ' Apollo Health City Campus, Jubilee Hills, Hyderabad - ' ie all strings before \n预期 output - ' Apollo Health City Campus, Jubilee Hills, Hyderabad - '即之前的所有字符串 \n

why not simply split using \n and get the last string?为什么不简单地使用\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])

If you are sure that the string will contain a pincode.如果您确定该字符串将包含一个密码。 ie 6 digit number, another approach could be:即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)

I have added a check for 6 digit in a string only.我只在一个字符串中添加了一个 6 位数字的检查。 you can modify according to your needs.您可以根据自己的需要进行修改。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM