我正在处理一些原始文本,并希望将所有多个空格替换为一个空格。通常,会使用 stringr's str_squish,但不幸的是它也删除了我必须保留的换行符(\n 和 \r)。
任何想法?以下是我的尝试。非常感谢!
library(tidyverse)
x <- "hello \n\r how are you \n\r all good?"
str_squish(x)
#> [1] "hello how are you all good?"
str_replace_all(x, "[:space:]+", " ")
#> [1] "hello how are you all good?"
str_replace_all(x, "\\s+", " ")
#> [1] "hello how are you all good?"
Run Code Online (Sandbox Code Playgroud)
由reprex 包(v0.3.0)于 2020-07-01 创建
使用stringr,您可以使用\h简写字符类来匹配任何水平空格。
library(stringr)
x <- "hello \n\r how are you \n\r all good?"
x <- str_replace_all(x, "\\h+", " ")
## [1] "hello \n\r how are you \n\r all good?"
Run Code Online (Sandbox Code Playgroud)
在基本 R 中,您也可以将它与 PCRE 模式一起使用:
gsub("\\h+", " ", x, perl=TRUE)
Run Code Online (Sandbox Code Playgroud)
请参阅在线 R 演示。
如果您打算仍然匹配除 CR 和 LF 符号之外的任何空白(包括一些 Unicode 换行符),您可以简单地使用[^\S\r\n]模式:
str_replace_all(x, "[^\\S\r\n]+", " ")
gsub("[^\\S\r\n]+", " ", x, perl=TRUE)
Run Code Online (Sandbox Code Playgroud)