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

问题描述 投票:135回答:8

因此" xx yy 11 22 33 "将变为"xxyy112233"。我该如何实现?

regex r string grep r-faq
8个回答
233
投票

通常,我们需要一个矢量化的解决方案,所以这是一个更好的测试示例:

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

基础R方法:gsub

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

fixed = FALSE

如DWin所指出的,在这种情况下gsub(" ", "", x, fixed = TRUE) ## [1] "xy" "←→" ## [3] "\t\n\r\v\fx\t\n\r\v\fy\t\n\r\v\f" NA 不是必需的,但由于匹配固定字符串比匹配正则表达式要快,因此提供了更好的性能。

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

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 是R特定的正则表达式组,它匹配所有空格字符。 "[:space:]"是与语言无关的正则表达式,可以执行相同的操作。


"[:space:]"方法:\sstringr

str_replace_all在基本R函数的周围提供了更多人类可读的包装器(尽管自2014年12月起,开发版本在str_trim的顶部建立了一个分支,如下所述)。使用[stringr,上述命令的等效项是:

stringi

[str_replace_all][3]还具有library(stringr) str_replace_all(x, fixed(" "), "") str_replace_all(x, space(), "") 功能,该功能仅删除前导和尾随空格。

stringr

str_trim方法:str_trimstr_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

stringi建立在与平台无关的stri_replace_all_charclass上,并且具有广泛的字符串处理功能集。上面的stri_trim是:

stringi

此处ICU library是被视为空白的Unicode代码点集的替代语法,等效于equivalentslibrary(stringi) stri_replace_all_fixed(x, " ", "") stri_replace_all_charclass(x, "\\p{WHITE_SPACE}", "") "\\p{WHITE_SPACE}"。对于更复杂的正则表达式替换,还有"\\p{WHITE_SPACE}"

["[[:space:]]"也有"\\s"

space()

17
投票

我刚刚学习了“ stringr”包,使用str_trim(,side =“ both”)从字符串的开头和结尾删除空格,但是它也具有替换功能,因此:]]

stri_replace_all_regex

7
投票

[请注意,以上文字说明仅删除空格。如果您还想删除制表符或换行,请使用stringi包中的trim functions


7
投票

使用a <- " xx yy 11 22 33 " str_replace_all(string=a, pattern=" ", repl="") [1] "xxyy112233" 来匹配任何种类的水平空白字符。


6
投票
stringi

4
投票

tidyverse软件包library(stringi) stri_replace_all_charclass(" ala \t ma \n kota ", "\\p{WHITE_SPACE}", "") ## [1] "alamakota" 中的函数[[:blank:]]发挥了魔力!


0
投票

这样,您可以从数据框中的所有字符变量中删除所有空格。如果您只想选择一些变量,请使用x = "xx yy 11 22 33" gsub(" ", "", x) > [1] "xxyy112233" str_squish()


-1
投票

从字符串库,您可以尝试以下操作:

© www.soinside.com 2019 - 2024. All rights reserved.