大多数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"但这并不意味着:
stri_replace_all(str,
regex="(?<=[a-z])([A-Z])",
replacement=" \\1")
# "this 1s 1amel 1ase ain't 1t"发布于 2016-08-19 11:59:39
如果您查看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"发布于 2016-08-19 11:01:57
在这两种情况下,下面的选项都应该返回相同的输出。
pat <- "(?<=[a-z])(?=[A-Z])"
str_replace_all(str, pat, " ")
#[1] "this Is Camel Case aint It"
stri_replace_all(str, regex=pat, " ")
#[1] "this Is Camel Case aint It"根据?stri_replace_all的帮助页面,有一些例子表明使用$1、$2进行替换。
stri_replace_all_regex('123|456|789', '(\\p{N}).(\\p{N})', '$2-$1')因此,如果我们将\\1替换为$1,那么它应该可以工作。
stri_replace_all(str, regex = "(?<=[a-z])([A-Z])", " $1")
#[1] "this Is Camel Case aint It"https://stackoverflow.com/questions/39036688
复制相似问题