如何从字符串中删除所有空格?

waa*_*ers 131 regex string grep r r-faq

所以" xx yy 11 22 33 "会成为"xxyy112233".我怎样才能做到这一点?

Ani*_*iko 228

一般来说,我们需要一个矢量化的解决方案,所以这里有一个更好的测试示例:

whitespace <- " \t\n\r\v\f" # space, tab, newline, 
                            # carriage return, vertical tab, form feed
x <- c(
  " x y ",           # spaces before, after and in between
  " \u2190 \u2192 ", # contains unicode chars
  paste0(            # varied whitespace     
    whitespace, 
    "x", 
    whitespace, 
    "y", 
    whitespace, 
    collapse = ""
  ),   
  NA                 # missing
)
## [1] " x y "                           
## [2] " ? ? "                           
## [3] " \t\n\r\v\fx \t\n\r\v\fy \t\n\r\v\f"
## [4] NA
Run Code Online (Sandbox Code Playgroud)

基础R方法: gsub

gsub用另一个字符串替换string(fixed = TRUE)或正则表达式(fixed = FALSE,默认值)的所有实例.要删除所有空格,请使用:

gsub(" ", "", x, fixed = TRUE)
## [1] "xy"                            "??"             
## [3] "\t\n\r\v\fx\t\n\r\v\fy\t\n\r\v\f" NA 
Run Code Online (Sandbox Code Playgroud)

正如DWin所指出的那样,在这种情况下fixed = TRUE不是必需的,但提供稍好的性能,因为匹配固定字符串比匹配正则表达式更快.

如果要删除所有类型的空格,请使用:

gsub("[[:space:]]", "", x) # note the double square brackets
## [1] "xy" "??" "xy" NA 

gsub("\\s", "", x)         # same; note the double backslash

library(regex)
gsub(space(), "", x)       # same
Run Code Online (Sandbox Code Playgroud)

"[:space:]"是一个匹配所有空格字符的特定于R的正则表达式组. \s是一个与语言无关的正则表达式,可以完成同样的事情.


stringr方法:str_replace_allstr_trim

stringr在基本R函数周围提供了更多人类可读的包装器(尽管截至2014年12月,开发版本具有构建在其上的分支stringi,如下所述).上述命令的等价物,使用[ str_replace_all][3],是:

library(stringr)
str_replace_all(x, fixed(" "), "")
str_replace_all(x, space(), "")
Run Code Online (Sandbox Code Playgroud)

stringr还有一个str_trim只删除前导和尾随空格的函数.

str_trim(x) 
## [1] "x y"          "? ?"          "x \t\n\r\v\fy" NA    
str_trim(x, "left")    
## [1] "x y "                   "? ? "    
## [3] "x \t\n\r\v\fy \t\n\r\v\f" NA     
str_trim(x, "right")    
## [1] " x y"                   " ? ?"    
## [3] " \t\n\r\v\fx \t\n\r\v\fy" NA      
Run Code Online (Sandbox Code Playgroud)

stringi方法:stri_replace_all_charclassstri_trim

stringi基于独立于平台的ICU库构建,并具有广泛的字符串操作功能.以上的等价物是:

library(stringi)
stri_replace_all_fixed(x, " ", "")
stri_replace_all_charclass(x, "\\p{WHITE_SPACE}", "")
Run Code Online (Sandbox Code Playgroud)

这里"\\p{WHITE_SPACE}"是对于该组被认为是空白,相当于Unicode码位的替换的语法"[[:space:]]","\\s"space().对于更复杂的正则表达式替换,也有stri_replace_all_regex.

stringi还有修剪功能.

stri_trim(x)
stri_trim_both(x)    # same
stri_trim(x, "left")
stri_trim_left(x)    # same
stri_trim(x, "right")  
stri_trim_right(x)   # same
Run Code Online (Sandbox Code Playgroud)

  • 如果您查看http://flyordie.sin.khk.be/2011/05/04/day-35-replacing-characters/或只需键入?regex,那么您会看到[:space:]用于"Space"字符:制表符,换行符,垂直制表符,换页符,回车符和空格." 这比单独的空间要多得多 (5认同)
  • @Aniko。您是否有理由使用fixed = TRUE? (2认同)
  • @DWin如果R知道它不必调用正则表达式内容,那么它可能更快。在这种情况下,它实际上并没有任何区别,我只是习惯这样做。 (2认同)

小智 17

我刚刚学习了"stringr"包,用str_trim(,side ="both")从字符串的开头和结尾删除空格,但它还有一个替换函数,以便:

a <- " xx yy 11 22 33 " 
str_replace_all(string=a, pattern=" ", repl="")

[1] "xxyy112233"
Run Code Online (Sandbox Code Playgroud)

  • stringr包对每个编码都不适用.stringi包是更好的解决方案,更多信息请查看https://github.com/Rexamine/stringi (3认同)

bar*_*nus 7

请注意,上面写的灵魂只会删除空间.如果您还想stri_replace_all_charclassstringi包中删除制表符或新行使用.

library(stringi)
stri_replace_all_charclass("   ala \t  ma \n kota  ", "\\p{WHITE_SPACE}", "")
## [1] "alamakota"
Run Code Online (Sandbox Code Playgroud)

  • 在使用`stringi`几个月后,看到/了解它是多么强大和高效,它已成为我的字符串操作的首选包.你们做了很棒的工作. (5认同)
  • `stringi`包现在在CRAN上,享受!:) (4认同)

Avi*_*Raj 7

使用[[:blank:]]匹配任何种类的水平white_space字符.

gsub("[[:blank:]]", "", " xx yy 11 22  33 ")
# [1] "xxyy112233"
Run Code Online (Sandbox Code Playgroud)


ZWL*_*ZWL 6

x = "xx yy 11 22 33"

gsub(" ", "", x)

> [1] "xxyy112233"
Run Code Online (Sandbox Code Playgroud)


dam*_*oni 6

tidyversestr_squish()stringr中的函数发挥了神奇的作用!

library(dplyr)
library(stringr)

df <- data.frame(a = c("  aZe  aze s", "wxc  s     aze   "), 
                 b = c("  12    12 ", "34e e4  "), 
                 stringsAsFactors = FALSE)
df <- df %>%
  rowwise() %>%
  mutate_all(funs(str_squish(.))) %>%
  ungroup()
df

# A tibble: 2 x 2
  a         b     
  <chr>     <chr> 
1 aZe aze s 12 12 
2 wxc s aze 34e e4
Run Code Online (Sandbox Code Playgroud)

  • 请不要链接到代码。将其添加到您的答案的正文中并在此处进行解释,以使您的答案更具长期价值。 (4认同)
  • 我不明白这如何回答这个问题。`str_squish` 不会删除所有空格。它只是修剪并用多个空格替换一个空格。 (4认同)

小智 6

可以考虑另一种方法

library(stringr)
str_replace_all(" xx yy 11 22  33 ", regex("\\s*"), "")

#[1] "xxyy112233"
Run Code Online (Sandbox Code Playgroud)

\\s:匹配空格、制表符、垂直制表符、换行符、换页符、回车符

*: 至少匹配0次