python - 在字符前提取单词
问题描述
我正在尝试提取Y
边界分隔之前的任何单词。因为我试图将每一行视为使用(?m)
标志的单独记录并尝试捕获\w+
前瞻\s+Y
,但我只能打印第一场比赛,而不是第二场比赛(IMP1
)。
print(foo)
this is IMP Y text
and this is also IMP1 Y text
this is not so IMP2 N text
Y is not important
当前徒劳的尝试:
>>> m = re.search('(?m).*?(\w+)(?=\s+Y)',foo)
>>> m.groups()
('IMP',)
>>>
>>> m = re.search('(?m)(?<=\s)(\w+)(?=\s+Y)',foo)
>>> m.groups()
('IMP',)
>>>
预期结果是:
('IMP','IMP1')
解决方案
您可以使用
\w+(?=[^\S\r\n]+Y\b)
请参阅正则表达式演示。细节:
\w+
- 一个或多个字母/数字/下划线 -(?=[^\S\r\n]+Y\b)
紧随其后的是一个或多个除 CR 和 LF 之外的空格,然后Y
作为一个完整的单词(\b
是单词边界)。
查看Python 演示:
import re
foo = "this is IMP Y text\nand this is also IMP1 Y text\nthis is not so IMP2 N text\nY is not important"
print(re.findall(r'\w+(?=[^\S\r\n]+Y\b)', foo))
# => ['IMP', 'IMP1']
推荐阅读
- drupal - Drupal 8:如何在表单标签中添加一个类
- laravel - Laravel:用于表演的 API 嵌套资源
- reactjs - React Redux 如何将有效负载目标值传递给操作
- php - 在ajax成功的表中显示数据
- matlab - 使用一个函数作为另一个函数的输入
- git - 推送到.git但拒绝错误的用户,终于解决了
- javascript - 减小材质 ui 中扩展面板的大小
- sql-server - 存储过程在 asp.net web api 中返回错误值
- angular - angular 6 中 jquery 的 $.each 的替代品
- python - 相同的 for_loop 代码,第二次运行打印不同的结果