【问题标题】:remove extra white space and add space after specific symbol删除额外的空格并在特定符号后添加空格
【发布时间】:2020-09-01 05:00:12
【问题描述】:

我有一个字符向量,我想删除多余的空格并在 ; 之后留下一个空格,非常感谢,

text <- "Mezgebo Gk;     Ymesel T;Tegegne G"

我厌倦了这些

text <- gsub("\\s+"," ",text)
text <- sub(";", "; ", text)

预期结果

"Mezgebo Gk; Ymesel T; Tegegne G"

【问题讨论】:

  • 试试gsub(";\\s*", "; ", text)。这会将所有 ; 和后面的空格(0 或大于 0)替换为 ; 并且只有一个空格

标签: r string data-manipulation


【解决方案1】:

你可以试试下面的代码

gsub("(?<=;)(\\s+)?"," ",text,perl = TRUE)

给了

[1] "Mezgebo Gk; Ymesel T; Tegegne G"

【讨论】:

    【解决方案2】:

    有一个方便的函数专门用于删除多余的空格,无论其在字符串中的位置如何:

    library(tidyverse)
    str_squish("Mezgebo Gk;     Ymesel T;Tegegne G")
    
    [1] "Mezgebo Gk; Ymesel T;Tegegne G"
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-05-31
      • 1970-01-01
      • 1970-01-01
      • 2021-12-20
      • 1970-01-01
      • 2017-02-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多