删除数字之间的空格而不将单独的浮点数粘合在一起

Remove spaces between digits without gluing separate float numbers together

在 R 中,我有一个这样的字符串向量:

str_vec <- c("1 9.7 1 0.8", "7.6 7.5", "3.7 13.5", "8.6 1 5.8")

我需要删除数字中的空格。即,我希望此向量的第一个和最后一个字符串为:

"19.7 10.8"
"8.6 15.8"

我看到 java 语言。这看起来很有用,但我无法将其翻译成 R。

我不确定这是不是你想要的

lapply(
  strsplit(str_vec, split = "(?<=\.\d)\s", perl = TRUE),
  function(x) gsub("\s", "", x)
)

这给出了

[[1]]
[1] "19.7" "10.8"

[[2]]
[1] "7.6" "7.5"

[[3]]
[1] "3.7"  "13.5"

[[4]]
[1] "8.6"  "15.8"

不知道这在 R 中是如何完成的,但在 python

中是这样完成的
import re

regex = r"(\d)\s([\.\d]+)"

test_str = "\"1 9.7 1 0.8\", \"7.6 7.5\", \"3.7 13.5\", \"8.6 1 5.8\""

subst = ""


result = re.sub(regex, subst, test_str, 0, re.MULTILINE)

if result:
    print (result)

Link 至 Regex101

或者:

library(stringr)

str_vec <- c("1 9.7 1 0.8", "7.6 7.5", "3.7 13.5", "8.6 1 5.8")

want <- str_remove_all(str_vec, "\s")
want <- str_replace(want, "(\d+\.\d)(\d+\.\d)", "\1 \2")
want
#"19.7 10.8" "7.6 7.5"   "3.7 13.5"  "8.6 15.8" 

您可以使用

library(stringr)
x <- c("1 9.7 1 0.8", "7.6 7.5", "3.7 13.5", "8.6 1 5.8")
str_replace_all(x, "\d(?:\s*\d)*\.\d+", function(z) str_replace_all(z, "\s+", ""))
# => [1] "19.7 10.8" "7.6 7.5"   "3.7 13.5"  "8.6 15.8" 

参见R demo online and the regex demo

正则表达式详细信息

  • \d - 一个数字
  • (?:\s*\d)* - 出现 0 次或多次 0 次或多次空格后跟一个数字
  • \. - 一个点
  • \d+ - 一位或多位数字。

仅使用 str_replace_all(z, "\s+", "").

从每个匹配项中删除所有空格