【问题标题】:Removing white spaces after specific symbol ";"删除特定符号“;”后的空格
【发布时间】:2018-02-05 21:36:12
【问题描述】:

我有一个关于删除列数据框中字符文本中的空格的问题。这是我的数据框列:

head(data$HO)
[1] "Lidar; Wind field; Temperature; Aerosol; Fabry-Perot etalon"                             
[2] "Compressive ghost imaging; Guided filter; Single-pixel imaging"    

这个问题与这个link 不同,因为我只想删除符号“;”后面的空格,所以输出应该是这样的:

head(data$HO)
[1] "Lidar;Wind field;Temperature;Aerosol;Fabry-Perot etalon"                             
[2] "Compressive ghost imaging;Guided filter;Single-pixel imaging"    

我试过了

data$HO <- gsub("\\;s", ";",data$HO)

但它不起作用。

有什么建议吗?

【问题讨论】:

标签: r trim gsub


【解决方案1】:

您可以使用;\s+ 模式并替换为;

> x <- c("Lidar; Wind field; Temperature; Aerosol; Fabry-Perot etalon", "Compressive ghost imaging; Guided filter; Single-pixel imaging")
> gsub(";\\s+", ";", x)
[1] "Lidar;Wind field;Temperature;Aerosol;Fabry-Perot etalon"     
[2] "Compressive ghost imaging;Guided filter;Single-pixel imaging"

图案细节:

  • ; - 分号
  • \s+ - 一个或多个空格字符。

请参阅regex demo

解决方案的更多变体:

gsub("(*UCP);\\K\\s+", "", x, perl=TRUE)
gsub(";[[:space:]]+", ";", x)

【讨论】:

    【解决方案2】:

    另一种可能的解决方案是使用 look-behind ?&lt;= 令牌。只需检查\s+ 后面的; 并将空格替换为空。

    v <- c("Lidar; Wind field; Temperature; Aerosol; Fabry-Perot etalon", 
          "Compressive ghost imaging; Guided filter; Single-pixel imaging")
    
    gsub("(?<=;)\\s+", "", v, perl = TRUE)
    
    # Result:
    # [1] "Lidar;Wind field;Temperature;Aerosol;Fabry-Perot etalon"     
    # [2] "Compressive ghost imaging;Guided filter;Single-pixel imaging"
    

    【讨论】:

      猜你喜欢
      • 2020-09-01
      • 1970-01-01
      • 2021-09-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-18
      • 2014-07-20
      相关资源
      最近更新 更多