【发布时间】:2019-11-29 17:29:50
【问题描述】:
我是编程和 Python 的新手,所以如果这是一个明显的问题,我深表歉意。我尝试在这个网站上查看类似的问题,但解决方案似乎超出了我的能力范围。
问题:考虑以下文本:
12/19 保罗 1/20
1/20 雅各布 10/2
使用模块 re,从上面提取名称。换句话说,你的输出应该是:
['保罗','雅各布']
首先,我尝试使用积极的环顾四周。我试过了:
import re
name_regex=re.compile(r'''(
(?<=\d{1,2}/\d{1,2}\s) #looks for one or two digits followed by a forward slash followed by one or two digits, followed by a space
.*? #looks for anything besides the newline in a non-greedy manner (is the non-greedy part necessary? I am not sure...)
(?=\s\d{1,2}/\d{1,2}) #looks for a space followed by one or two digits followed by a forward slash followed by one or two digits
)''', re.VERBOSE)
text=str("12/19 Paul 1/20\n1/20 Jacob 10/2")
print(name_regex.findall(text))
但是,上面会产生错误:
re.error: look-behind requires fixed-width pattern
通过阅读类似的问题,我相信这意味着环顾四周不能有可变长度(即,它们不能寻找“1 或 2 位数字”)。
但是,我该如何解决这个问题?
任何帮助将不胜感激。特别是适合像我这样的几乎完全初学者的帮助!
PS。最终,被日期包围的名字列表可能会很长。日期可以有一个或两个数字,用斜线分隔。我只是想举一个最小的工作示例。
谢谢!
【问题讨论】:
-
@Emma 谢谢,几乎成功了!我得到以下输出:['Paul', '1/20 Jacob']。所以几乎是我想要的。知道如何改进它吗?
标签: python regex regex-lookarounds regex-greedy