python - 在 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 之前的所有字符串
解决方案
为什么不简单地使用拆分\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 位数字的检查。您可以根据自己的需要进行修改。
推荐阅读
- c# - 将和列表划分为满足条件的组的问题
- python - pip 安装洋红色时在终端上收到错误
- python - 使用 List 参数调用 marshmallow 验证的 GET 端点
- node.js - 如何使用 node.js 查找文件扩展名更改?
- angular - 在 ionic 2 中试图从一页移动(导航)到另一页,但它不起作用?
- java - 试图用java计算向量
- python - 获取 IndexError:尝试将技术指标应用于股票信息的 pandas DataFrame 时,单个位置索引器超出范围
- go - 通过 GRPC 服务器为 graphql 服务器提供服务
- c# - 从 API 控制器从服务器数据库检索数据时缺少实体
- html - HTML5 日期时间-本地选择器自定义占位符