在 gregexpr 和 str_extract_all 函数中进行量化的交替

Alternaion with quantifies in gregexpr and str_extract_all function

gregexprstr_extract_all 函数中进行量化的交替

require(stringr)
gregexpr(pattern = "(h|a)*", "xxhx")
[[1]]
[1] 1 2 3 4
attr(,"match.length")
[1] 0 0 1 0
attr(,"useBytes")
[1] TRUE

str_extract_all(pattern = "(h|a)*", "xxhx")
[[1]]
[1] ""  ""  "h" ""  ""

为什么gregexpr表示3个空洞而str_extract_all表示4个空洞

这是 TRE (gregexpr) 和 ICU (str_extract_all) 正则表达式引擎处理空(也称为 "zero length")正则表达式匹配的区别。 TRE 正则表达式在零长度匹配后推进正则表达式索引,而 ICU 允许对同一位置进行两次测试。

如果您使用替换函数,两个引擎尝试的位置将变得显而易见:

> gsub("(h|a)*", "-\1", "xxhx")
[1] "-x-x-hx-"
> str_replace_all("xxhx", "(h|a)*", "-\1")
[1] "-x-x-h-x-"

TRE 引擎匹配 h 并在 x 之后移动索引,而 ICU 引擎匹配 h 并在 h 之后停止 x 以匹配前面的空位置。