您可以使用re.findall 方法:
import re
txt = "U3951583\n Hi there my name is Harry. Check out http://www.harryresume.com. That's my website. \n U39501492\n That's a cool website. \n U5235098\n I'll have a look too"
print(re.findall(r'\bU\d{7,8}\b.*?(?=\bU\d{7,8}\b|\Z)', txt, re.S))
# => ["U3951583\n Hi there my name is Harry. Check out http://www.harryresume.com. That's my website. \n ", "U39501492\n That's a cool website. \n ", "U5235098\n I'll have a look too"]
见Python demo
分别获取名称和内容的变体:
for name, content in re.findall(r'\b(U\d{7,8})\b(.*?)(?=\bU\d{7,8}\b|\Z)', txt, re.S):
print("{}:{}".format(name.strip(), content.strip()))
输出:
U3951583:Hi there my name is Harry. Check out http://www.harryresume.com. That's my website.
U39501492:That's a cool website.
U5235098:I'll have a look too
见this Python demo
使用的正则表达式是
\b(U\d{7,8})\b(.*?)(?=\bU\d{7,8}\b|\Z)
见regex demo
详情
-
\b - 单词边界(没有字母/数字/_ 可以立即出现在当前位置的左侧)
-
(U\d{7,8}) - 第 1 组:U 和 7 位或 8 位数字
-
\b - 单词边界
-
(.*?) - 第 2 组:任何 0+ 个字符,尽可能少
-
(?=\bU\d{7,8}\b|\Z) - 正向前瞻,要求上述模式(名称模式)紧邻当前位置的右侧或 (|) 字符串结尾 (\Z)。
Python 3.7+
在最新的 Python 版本中,您可以使用与空字符串匹配的模式 re.split:
>>> import re
>>> txt = "U3951583\n Hi there my name is Harry. Check out http://www.harryresume.com. That's my website.
\n U39501492\n That's a cool website. \n U5235098\n I'll have a look too"
>>> print(re.split(r'(?!^)(?=\bU\d{7,8}\b)', txt))
["U3951583\n Hi there my name is Harry. Check out http://www.harryresume.com. That's my website. \n ", "U3
9501492\n That's a cool website. \n ", "U5235098\n I'll have a look too"]
因此,如果您不需要单独获取名称和内容,这可能是一种更简单的方法。