在str_replace/stri_replace中使用捕获的组 - stringi vs stringr

asa*_*ica 6 r stringi

大多数stringr函数只是相应stringi函数的包装器.str_replace_all就是其中之一.然而我的代码不适stri_replace_all用于相应的stringi函数.

我正在编写一个快速正则表达式来将(一个子集的)驼峰转换为间隔的单词.

我很困惑为什么这样做:

str <- "thisIsCamelCase aintIt"
stringr::str_replace_all(str, 
                         pattern="(?<=[a-z])([A-Z])", 
                         replacement=" \\1")
# "this Is Camel Case ain't It"
Run Code Online (Sandbox Code Playgroud)

而这不是:

stri_replace_all(str, 
                 regex="(?<=[a-z])([A-Z])", 
                 replacement=" \\1")
# "this 1s 1amel 1ase ain't 1t"
Run Code Online (Sandbox Code Playgroud)

hrb*_*str 8

如果您查看源代码,stringr::str_replace_all您将看到它调用fix_replacement(replacement)\\#捕获组引用转换为$#.但在帮助stringi:: stri_replace_all也清楚地表明,你用$1,$2等的捕捉组.

str <- "thisIsCamelCase aintIt"
stri_replace_all(str, regex="(?<=[a-z])([A-Z])", replacement=" $1")
## [1] "this Is Camel Case aint It"
Run Code Online (Sandbox Code Playgroud)