【问题标题】:using captured groups in str_replace / stri_replace - stringi vs stringr [duplicate]在 str_replace / stri_replace 中使用捕获的组 - stringi vs stringr [重复]
【发布时间】:2016-08-19 10:26:43
【问题描述】:

大多数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"

【问题讨论】:

  • 一个选项是stri_replace_all(str, regex = "(?&lt;=[a-z])(?=[A-Z])", replacement=" ")

标签: r stringi


【解决方案1】:

如果您查看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"

【讨论】:

    【解决方案2】:

    以下选项应在两种情况下返回相同的输出。

    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"
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多