在 str_replace / stri_replace 中使用捕获的组 - stringi vs stringr
using captured groups in str_replace / stri_replace - stringi vs stringr
大多数 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"
下面的选项在两种情况下应该return相同的输出。
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
的帮助页面,有例子提示</code>,<code>
用于替换
stri_replace_all_regex('123|456|789', '(\p{N}).(\p{N})', '-')
因此,如果我们将 \1
替换为 </code></p>,它应该可以工作
<pre><code>stri_replace_all(str, regex = "(?<=[a-z])([A-Z])", " ")
#[1] "this Is Camel Case aint It"
如果您查看 stringr::str_replace_all
的源代码,您会发现它调用 fix_replacement(replacement)
将 \#
捕获组引用转换为 $#
。但是 stringi:: stri_replace_all
上的帮助也清楚地表明您使用 </code>、<code>
等作为捕获组。
str <- "thisIsCamelCase aintIt"
stri_replace_all(str, regex="(?<=[a-z])([A-Z])", replacement=" ")
## [1] "this Is Camel Case aint It"
大多数 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"
下面的选项在两种情况下应该return相同的输出。
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
的帮助页面,有例子提示</code>,<code>
用于替换
stri_replace_all_regex('123|456|789', '(\p{N}).(\p{N})', '-')
因此,如果我们将 \1
替换为 </code></p>,它应该可以工作
<pre><code>stri_replace_all(str, regex = "(?<=[a-z])([A-Z])", " ")
#[1] "this Is Camel Case aint It"
如果您查看 stringr::str_replace_all
的源代码,您会发现它调用 fix_replacement(replacement)
将 \#
捕获组引用转换为 $#
。但是 stringi:: stri_replace_all
上的帮助也清楚地表明您使用 </code>、<code>
等作为捕获组。
str <- "thisIsCamelCase aintIt"
stri_replace_all(str, regex="(?<=[a-z])([A-Z])", replacement=" ")
## [1] "this Is Camel Case aint It"