首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在str_replace / stri_replace - stringr与stringr中使用捕获的组

在str_replace / stri_replace - stringr与stringr中使用捕获的组
EN

Stack Overflow用户
提问于 2016-08-19 10:26:43
回答 2查看 2.3K关注 0票数 7

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

我正在写一个快速的正则表达式,将骆驼的一个子集转换成空格字。

我很不明白为何这样做是可行的:

代码语言:javascript
复制
str <- "thisIsCamelCase aintIt"
stringr::str_replace_all(str, 
                         pattern="(?<=[a-z])([A-Z])", 
                         replacement=" \\1")
# "this Is Camel Case ain't It"

但这并不意味着:

代码语言:javascript
复制
stri_replace_all(str, 
                 regex="(?<=[a-z])([A-Z])", 
                 replacement=" \\1")
# "this 1s 1amel 1ase ain't 1t"
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2016-08-19 11:59:39

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

代码语言:javascript
复制
str <- "thisIsCamelCase aintIt"
stri_replace_all(str, regex="(?<=[a-z])([A-Z])", replacement=" $1")
## [1] "this Is Camel Case aint It"
票数 10
EN

Stack Overflow用户

发布于 2016-08-19 11:01:57

在这两种情况下,下面的选项都应该返回相同的输出。

代码语言:javascript
复制
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进行替换。

代码语言:javascript
复制
stri_replace_all_regex('123|456|789', '(\\p{N}).(\\p{N})', '$2-$1')

因此,如果我们将\\1替换为$1,那么它应该可以工作。

代码语言:javascript
复制
stri_replace_all(str, regex = "(?<=[a-z])([A-Z])", " $1")
#[1] "this Is Camel Case aint It"
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/39036688

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档