【问题标题】:R regex to replace all periods after variable number of periods preceeded by space/start of lineR正则表达式替换可变数量的句点之后的所有句点,前面有空格/行首
【发布时间】:2019-03-02 21:59:20
【问题描述】:

我有以下字符串。我想用字母 i 替换最多 3 个句点之后的所有句点。

 x <- c(
    ".. ........ .......    ",
    "... ........ .......          ",
    ". ..... .......  . .. ... .... ",
    ".. ..... ...........  ....      "
)

期望的输出:

x <- c(
    ".. ...iiiii ...iiii    ",
    "... ...iiiii ...iiii          ",
    ". ...ii ...iiii  . .. ... ...i ",
    ".. ...ii ...iiiiiiii  ...i      "
)

我非常错误的尝试:

gsub('(?:(?:^|\\s))(x)', '\\U\\1', gsub('\\.', 'x', x), perl = TRUE)

【问题讨论】:

    标签: r regex pcre


    【解决方案1】:

    试试正则表达式(?&lt;=\.{3})(\S+?)

    这会将 3 个句点之后的所有句点替换为 i
    regex

    gsub('(?<=\\.{3})(\\S+?)', 'i', x, perl = TRUE)
    

    【讨论】:

    • 或者这样简单很多!不知道它会像那样匹配多次。
    【解决方案2】:

    这是一种获得所需结果的方法,虽然有点笨拙但很有效。基本上,尝试一次性完成的问题似乎是你不知道替换会有多大,所以你可以一次做一个角色来解决它......

    x <- c(
      ".. ........ .......    ",
      "... ........ .......          ",
      ". ..... .......  . .. ... .... ",
      ".. ..... ...........  ....      "
    )
    library(stringr)
    dots_to_i <- function(chr){
      pat_p <- "(?<=(^| )\\.{3})\\."
      pat_i <- "(?<=i)\\."
      while (any(str_detect(chr, pat_p)) | any(str_detect(chr, pat_i))){
        chr <- chr %>%
          str_replace_all(pat_p, "i") %>%
          str_replace_all(pat_i, "i")
      }
      return(chr)
    }
    dots_to_i(x)
    #> [1] ".. ...iiiii ...iiii    "          "... ...iiiii ...iiii          "  
    #> [3] ". ...ii ...iiii  . .. ... ...i "  ".. ...ii ...iiiiiiii  ...i      "
    

    reprex package (v0.2.0) 于 2018 年 9 月 26 日创建。

    【讨论】:

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