使用可选组获取最短匹配的问题
Issue getting the shortest match using optional groups
我想在 (this is)?.??.??(an)?.??.??(example sentence)
正则表达式中的每个组之间允许任何 0 到 2 个字符。它应该匹配以下字符串中的粗体文本:
blah blah. An example sentence
blah blah. This is an example sentence
Something something Example sentence
现在,在第一个示例中,匹配项是 ah. example sentence
。我想在“。”前加上2个问号。意味着正则表达式引擎更愿意匹配 0 个字符。
我在 MS Word 的 VBA 中使用正则表达式,由 CreateObject("vbscript.regexp")
实现,据我所知,它使用 VBScript 正则表达式风格,据我所知,它与 JavaScript风味。
When searching 0020002101
should 2.??.??.??101
not prefer 2101
to 20002101
?
Regex 引擎不能"prefer" 任何东西。它从左到右匹配。一旦找到 2
(第一个 2
),它就会开始匹配后续的子模式,并在找到匹配项时返回它。
在您的情况下,您需要使用可选组中的 .{0,2}
、
(this is.{0,2})?(an.{0,2})?(example sentence)
^^^^^^ ^^^^^^
参见regex demo。
如果可选字符串的顺序很重要,请将它们嵌套:
(this is.{0,2}(an.{0,2})?)?(example sentence)
参见 another regex demo。只有在 this is
之前找到具有 0 到 2 个字符的 this is
时,此正则表达式才会匹配其后具有 0 到 2 个字符的 an
。
我想在 (this is)?.??.??(an)?.??.??(example sentence)
正则表达式中的每个组之间允许任何 0 到 2 个字符。它应该匹配以下字符串中的粗体文本:
blah blah. An example sentence
blah blah. This is an example sentence
Something something Example sentence
现在,在第一个示例中,匹配项是 ah. example sentence
。我想在“。”前加上2个问号。意味着正则表达式引擎更愿意匹配 0 个字符。
我在 MS Word 的 VBA 中使用正则表达式,由 CreateObject("vbscript.regexp")
实现,据我所知,它使用 VBScript 正则表达式风格,据我所知,它与 JavaScript风味。
When searching
0020002101
should2.??.??.??101
not prefer2101
to20002101
?
Regex 引擎不能"prefer" 任何东西。它从左到右匹配。一旦找到 2
(第一个 2
),它就会开始匹配后续的子模式,并在找到匹配项时返回它。
在您的情况下,您需要使用可选组中的 .{0,2}
、
(this is.{0,2})?(an.{0,2})?(example sentence)
^^^^^^ ^^^^^^
参见regex demo。
如果可选字符串的顺序很重要,请将它们嵌套:
(this is.{0,2}(an.{0,2})?)?(example sentence)
参见 another regex demo。只有在 this is
之前找到具有 0 到 2 个字符的 this is
时,此正则表达式才会匹配其后具有 0 到 2 个字符的 an
。