原始数据:
# Case 1
1980 (reprint 1987)
# Case 2
1980 (1987 reprint)
捕获组:
{
publish: 1980,
reprint: 1987
}
要求:
- 匹配“转载”,从而将其年份段视为转载。
- 第一个匹配年份始终是发布年份。
当前方法:
# Match 2nd case but not the 1st case.
(?P<publish>\d{4}).*(?P<reprint>\d{4}(?=\sreprint.*))
# Match 1st case but not the 2nd case
(?P<publish>\d{4}).*(?<=reprint\s)(?P<reprint>\d{4})
我不确定如何合并上面的 2 个正则表达式。所以我必须重复匹配两次。或者,如果有关于如何在一个正则表达式下匹配两者的答案,那就更好了。
最佳答案
您可以交替使用这个单一的正则表达式。如果 reprint
组后跟 \sreprint
(由正前瞻断言)或者如果它前面是 reprint\s
(由断言积极的回顾)。
(?P<publish>\d{4}).*?(?P<reprint>(?:\d{4}(?=\sreprint)|(?<=reprint\s)\d{4}))
关于python - 如何在一个正则表达式下匹配两种模式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38289874/