此正则表达式示例中元组的意外行为
The unexpected behavior of an tuple in this regular expression example
我测试了这个正则表达式
test_reg = r"(?<=\(|\s)\d+\s?(?=((?:\s*(?:wh|www)[1-9]?\s?){1,3}))\b"
关于以下三个例子:
high energy densities (695 wh www ) at
high energy densities (695 wh www) at
high energy densities (695 wh www at
来自result (regex101),第一个例子中的')'莫名其妙导致匹配失败,删除它解决了问题。我不明白为什么。
((?:\s*(?:wh|www)[1-9]?\s?){1,3})
捕获组 #1 捕获 high energy densities (695 wh www ) at
中的可选白色 space,我们紧跟在 www
和 )
之后。当使用 </code> 使用该值时,无法 re-match 字符串的这一部分,因为反向引用是 non-backtracking 的。因此,末尾带有 space 的 <code>
值失败,因为单词边界 \b
与 space 和 )
之间的位置不匹配(两者都是是 non-word 个字符)。
因此,应删除第 1 组模式末尾的 \s?
,或将其移动(\s?
或 \s*
)到表达式的末尾:
test_reg = r"(?<=[(\s])\d+\s?(?=((?:\s*(?:wh|www)[1-9]?){1,3}))\b"
test_reg = r"(?<=[(\s])\d+\s?(?=((?:\s*(?:wh|www)[1-9]?){1,3}))\b\s?"
参见regex demo。
我测试了这个正则表达式
test_reg = r"(?<=\(|\s)\d+\s?(?=((?:\s*(?:wh|www)[1-9]?\s?){1,3}))\b"
关于以下三个例子:
high energy densities (695 wh www ) at
high energy densities (695 wh www) at
high energy densities (695 wh www at
来自result (regex101),第一个例子中的')'莫名其妙导致匹配失败,删除它解决了问题。我不明白为什么。
((?:\s*(?:wh|www)[1-9]?\s?){1,3})
捕获组 #1 捕获 high energy densities (695 wh www ) at
中的可选白色 space,我们紧跟在 www
和 )
之后。当使用 </code> 使用该值时,无法 re-match 字符串的这一部分,因为反向引用是 non-backtracking 的。因此,末尾带有 space 的 <code>
值失败,因为单词边界 \b
与 space 和 )
之间的位置不匹配(两者都是是 non-word 个字符)。
因此,应删除第 1 组模式末尾的 \s?
,或将其移动(\s?
或 \s*
)到表达式的末尾:
test_reg = r"(?<=[(\s])\d+\s?(?=((?:\s*(?:wh|www)[1-9]?){1,3}))\b"
test_reg = r"(?<=[(\s])\d+\s?(?=((?:\s*(?:wh|www)[1-9]?){1,3}))\b\s?"
参见regex demo。