python - 为什么这个正则表达式不匹配所有内容,直到第一个捕获组再次出现?
问题描述
我如何让它做到这一点?
现在它停在换行符处(就像在“芝加哥”之后一样)。或者,如果我使用 DOTALL,它只会匹配“Abbott A (1988)”,然后匹配字符串的其余部分直到最后。我希望它在下一次出现 (([\w\s]+)(([1|2]\d{3}))) 时停止,即..."Albu OB and Flyverbom M (2016 )”。等等等等。
欢迎任何指点。
pattern = r"(([\w\s]+)\(([1|2]\d{3})\))(.*)"
示例字符串
"Abbott A (1988) The System of Professions: An Essay on the Division of Expert Labor. Chicago,
IL: University of Chicago Press.
Albu OB and Flyverbom M (2016) Organizational transparency: conceptualizations, con-
ditions, and consequences. Business & Society. Epub ahead of print 13 July. DOI:
10.1177/0007650316659851.
Ananny M (2016) Toward an ethics of algorithms: convening, observation, probability, and timeli-
ness. Science, Technology & Human Values 41(1): 93–117. DOI: 10.1177/0162243915606523."
沙箱在这里
解决方案
您可以使用
(?sm)^([^()\n\r]+)\(([12]\d{3})\)(.*?)(?=^[^()\n\r]+\([12]\d{3}\)|\Z)
查看正则表达式演示
细节
(?sm)
-re.DOTALL
并re.MULTILINE
启用^
- 一行的开始([^()\n\r]+)
(
- 第 1 组:除,)
, CR 和 LF之外的一个或多个字符\(
- 一个(
([12]\d{3})
- 第 2 组:1
或2
然后任意 3 位数字\)
- 一个)
字符(.*?)
- 第3组:任何0+个字符,包括换行符,尽可能少,直到(但不包括匹配)第一个......(?=^[^()\r\n]+\([12]\d{3}\)|\Z)
- (一个正向前瞻,要求其模式立即出现在当前位置的右侧):^[^()\r\n]+\([12]\d{3}\)
- 与模式的开始相同,但没有组|
- 或者\Z
- 全文结束。
推荐阅读
- python-3.x - 如何使用 Open-AI GPT 构建特定领域的语言模型以生成自然语言?
- python - 变量过多的 KNN 模型
- python-3.x - 如何在 k-means 聚类中使用 tfidf 值
- docker - 在 Jenkins Slave Docker 容器中运行时,Jenkins Docker Pipeline 插件无法正常工作
- https - Mule4:HTTPS POST 的“远程关闭”错误
- ios - Getting memory leak in SwiftUI TextField
- ssl - 如何强制 iframe 使用已嵌入其他 https 网站的 https?
- java - Groovy trait 要求我实现它的所有超类的方法,而它已经在另一个接口上实现
- java - (android studio) can't change the "Webpage not available" page in webview
- mysql - How "ORDER BY" ordered if there are same value?