gpt4 book ai didi

python - 为什么这个正则表达式在第一个捕获组再次出现之前不匹配所有内容?

转载 作者:行者123 更新时间:2023-12-01 01:50:38 26 4
gpt4 key购买 nike

我该如何让它做到这一点?

现在它停在换行符处(例如“Chicago,”之后)。或者,如果我使用 DOTALL,它只匹配“Abbott A (1988)”,然后匹配字符串的其余部分,直到最后。我希望它在下一次出现 (([\w\s]+)(([1|2]\d{3}))) 时停止,即......“Albu OB 和 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."

沙箱 here

最佳答案

您可以使用

(?sm)^([^()\n\r]+)\(([12]\d{3})\)(.*?)(?=^[^()\n\r]+\([12]\d{3}\)|\Z)

请参阅regex demo

详细信息

  • (?sm) - 已启用 re.DOTALLre.MULTILINE
  • ^ - 行的开头
  • ([^()\n\r]+) - 第 1 组:除 (, ) 之外的一个或多个字符, CR 和 LF
  • \( - 一个 (
  • ([12]\d{3}) - 第 2 组:12,然后是任意 3 位数字
  • \) - 一个 ) 字符
  • (.*?) - 第 3 组:任何 0+ 个字符,包括换行符,尽可能少,直到第一个(但不包括匹配)...
  • (?=^[^()\r\n]+\([12]\d{3}\)|\Z) - (正向预测,需要存在它的模式紧邻当前位置的右侧):
    • ^[^()\r\n]+\([12]\d{3}\) - 与模式的开头相同,但没有组
    • | - 或
    • \Z - 整个文本的结尾。

关于python - 为什么这个正则表达式在第一个捕获组再次出现之前不匹配所有内容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50755084/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com