删除特定符号“;”后的空格

Removing white spaces after specific symbol ";"

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

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)

但它不起作用。

有什么建议吗?

您可以使用 ;\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)

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

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"