如何使用 r 和 stringr 删除数字和字符之间的 space

how to delete a space between a number and a character using r and stringr

我正在使用 R 和 stringr 进行一些字符串替换。我的文本类似于 "xxxxxx xxxx xxxxxx 1.5L xxxxx" 或 "xxxxxx xxxx xxxxxx 1.5 L xxxxx"。我的问题是:如何删除1.5和L之间的space?或者如何在它们之间添加 space?非常感谢。

我们可以使用库(stringi)

library(stringi)

text <- "1.5 L"
stri_replace_all(text,"1.5L" ,fixed = "1.5 L" )


[1] "1.5L

这应该有效

replacer=function(x)
{
  match_term=str_replace(str_match(x,'(?:[0-9]|\.)+(?: +)([A-Z])')[,1],' +','')
  return(str_replace(x,'([0-9]|\.)+( +)([A-Z])',match_term))
}

我们可以使用 sub

对单个捕获组执行此操作
sub("(\d+)\s+", "\1", str1)
#[1] "xxxxxx xxxx xxxxxx 1.5L xxxxx" "xxxxxx xxxx xxxxxx 1.5L xxxxx"

数据

str1 <- c("xxxxxx xxxx xxxxxx 1.5L xxxxx" , "xxxxxx xxxx xxxxxx 1.5 L xxxxx")