删除以 R 中出现次数为条件的空格
Removing white-spaces conditioned on number of occurrences in R
当2个非白色space字符之间连续的白色space个数时,我想从字符串中删除白色-spaces words 少于一定数量。
例如,
a <- c("I want only <5 white-spaces removed")
我知道我可以使用 gsub(' ', '', a)
删除所有 space。但是,我只想删除 两个非白色 space 字符 words 之间的 white-spaces white-space 小于5。所以我想要下面的
a_adj <- c("Iwant only <5 white-spacesremoved")
我试过了gsub('{,5} ', '', a)
。但它仍然会删除所有 white-spaces。有人可以帮忙吗?
谢谢
您可以使用
a_adj <- gsub("(?<=\S)\s{1,4}(?=\S)", "", a, perl=TRUE)
参见regex demo and the R demo。
(?<=\S)\s{1,4}(?=\S)
仅匹配任何非空白字符之间的 1 到 4 个空白。
详情
(?<=\S)
- 正后视要求紧靠当前位置左侧的非空白字符
\s{1,4}
- 1 到 4 个空白字符
(?=\S)
- 正前瞻要求紧靠当前位置右侧的非空白字符。
使用str_remove_all
library(stringr)
str_remove_all(a, "\s{1,4}(?! )")
当2个非白色space字符之间连续的白色space个数时,我想从字符串中删除白色-spaces words 少于一定数量。
例如,
a <- c("I want only <5 white-spaces removed")
我知道我可以使用 gsub(' ', '', a)
删除所有 space。但是,我只想删除 两个非白色 space 字符 words 之间的 white-spaces white-space 小于5。所以我想要下面的
a_adj <- c("Iwant only <5 white-spacesremoved")
我试过了gsub('{,5} ', '', a)
。但它仍然会删除所有 white-spaces。有人可以帮忙吗?
谢谢
您可以使用
a_adj <- gsub("(?<=\S)\s{1,4}(?=\S)", "", a, perl=TRUE)
参见regex demo and the R demo。
(?<=\S)\s{1,4}(?=\S)
仅匹配任何非空白字符之间的 1 到 4 个空白。
详情
(?<=\S)
- 正后视要求紧靠当前位置左侧的非空白字符\s{1,4}
- 1 到 4 个空白字符(?=\S)
- 正前瞻要求紧靠当前位置右侧的非空白字符。
使用str_remove_all
library(stringr)
str_remove_all(a, "\s{1,4}(?! )")