【问题标题】:Recursive stringi commands递归字符串命令
【发布时间】:2021-09-17 18:12:07
【问题描述】:

我正在使用一些 stringi 函数作为管道的一部分来清理一些字符串数据。

我希望这些函数是递归的,以便它们处理所有可能出现的 re,而不仅仅是第一个。我无法事前预测我需要运行该函数以正确清理数据的次数。

library(stringi)

test_1 <- "AAA A B BBB"
str_squish(str_remove(x, "\\b[A-Z]\\b"))
result <- "AAA B BBB"
desired <- "AAA BBB"

test_2 <- "AAA AA BBB BB CCCC"
str_replace(test_2,"(?<=\\s[A-Z]{2,3})\\s","")
result <- "AAA AABBB BB CCCC"
desired <- "AAA AABBB BBCCCC"

【问题讨论】:

  • 对于初学者,请尝试str_remove_all,我认为您的意思是library(stringr) 而不是library(stringi)

标签: r regex dplyr stringr stringi


【解决方案1】:

我建议在这里使用 base R 的 gsub,它可以替换全局正则表达式:

test_1 <- "AAA A B BBB"
result <- gsub("[ ]{2,}", " ", gsub("[ ]*\\b[A-Z]\\b[ ]*", " ", test_1))
result

[1] "AAA BBB"

【讨论】:

    【解决方案2】:

    也许使用gsub,它将执行替换所有匹配项:

    test_1 <- "AAA A B BBB"
    gsub(" +", " ", gsub("\\b[A-Z]\\b", "", test_1))
    #[1] "AAA BBB"
    
    test_2 <- "AAA AA BBB BB CCCC"
    gsub("(?<=\\s[A-Z]{2})\\s", "", test_2, perl=TRUE)
    #[1] "AAA AABBB BBCCCC"
    

    对于正则表达式(?&lt;=\\s[A-Z]{2,3})\\s,不清楚何时应遵守 2-3 的条件以及从何处开始:例如stringr::str_replace_all 会给:

    stringr::str_replace_all(test_2,"(?<=\\s[A-Z]{2,3})\\s","")
    #[1] "AAA AABBBBBCCCC"
    

    你也可以使用递归函数调用:

    f <- function(x) {
      y <- stringr::str_replace(x, "(?<=\\s[A-Z]{2,3})\\s","")
      if(x == y) x
      else f(y)
    }
    f(test_2)
    #[1] "AAA AABBB BBCCCC"
    

    【讨论】:

    • 非常感谢。对于第二个函数,我将其分成两部分,首先只运行 2 个字母条件,然后只运行 3 个字母条件
    猜你喜欢
    • 1970-01-01
    • 2013-04-06
    • 2017-10-28
    • 1970-01-01
    • 2013-02-08
    • 1970-01-01
    • 2011-02-03
    • 2015-02-16
    • 2015-10-25
    相关资源
    最近更新 更多