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

时间:2016-11-02 03:05:20

标签: r regex replace stringr

我正在使用R和stringr来做一些字符串替换。我的文字就像“xxxxxx xxxx xxxxxx 1.5L xxxxx”或“xxxxxx xxxx xxxxxx 1.5 L xxxxx”。我的问题是:如何删除1.5和L之间的空格?或者如何在它们之间添加空格?非常感谢。

3 个答案:

答案 0 :(得分:1)

我们可以使用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")

答案 1 :(得分:0)

我们可以使用库(stringi)

library(stringi)

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


[1] "1.5L

答案 2 :(得分:0)

这应该有效

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))
}