gpt4 book ai didi

c# - RegEx 模式仅在第二次交替时匹配

转载 作者:行者123 更新时间:2023-11-30 15:15:23 25 4
gpt4 key购买 nike

此模式取自此处已接受的答案:Regex - Extracting volume and chapter numbers from book titles

我去掉了 Vol/Volume 匹配,因为我只关心第 #s 章

正则表达式:(?i)(((?:C|chapter\s+)(\d+)) | (([a-z]+)\s+Chapter\b))

示例文本(粗体匹配项):

Blabla Vol.1 chapter 2
ABCD in the era of XYZ volume 2 First Chapter
Blah blah chapter 2 <------ wrong
Lablah V6C7 2002
FooBar Vol6 C3 by Dr. Foo Bar
Regex: A tool in Hell V1 Eleventh Chapter

注意“Blah blah chapter 2”匹配的是“blah chapter”而不是“chapter 2”

我做错了什么?

最佳答案

正则表达式引擎首先也是最重要的是从左到右逐个字符地进行匹配。只有在同一位置可以匹配多个备选方案时,备选方案的顺序才重要。

如果你想避免你的第二个选择来匹配章节,如果它后面跟着一个数字,你应该明确说明,例如使用一个消极的前瞻。

(?i)(((?:C|chapter\s+)(\d+))|(([a-z]+)\s+Chapter\b(?!\s+\d+)))

这将匹配如下:

Blabla Vol.1 chapter 2 --> chapter 2
ABCD in the era of XYZ volume 2 First Chapter --> First Chapter
Blah blah chapter 2 --> chapter 2
Lablah V6C7 2002 --> C7
FooBar Vol6 C3 by Dr. Foo Bar --> C3
Regex: A tool in Hell V1 Eleventh Chapter --> Eleventh Chapter

关于c# - RegEx 模式仅在第二次交替时匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52122158/

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