1

I am using R and stringr to do some string replacement. My text is like "xxxxxx xxxx xxxxxx 1.5L xxxxx" or "xxxxxx xxxx xxxxxx 1.5 L xxxxx".

My question is: how to delete the space between 1.5 and L? or How to add a space between them?

halfer
  • 19,824
  • 17
  • 99
  • 186
Feng Chen
  • 2,139
  • 4
  • 33
  • 62

3 Answers3

1

We can do this with a single capture group using sub

sub("(\\d+)\\s+", "\\1", str1)
#[1] "xxxxxx xxxx xxxxxx 1.5L xxxxx" "xxxxxx xxxx xxxxxx 1.5L xxxxx"

data

str1 <- c("xxxxxx xxxx xxxxxx 1.5L xxxxx" , "xxxxxx xxxx xxxxxx 1.5 L xxxxx")
akrun
  • 874,273
  • 37
  • 540
  • 662
0

We can use library(stringi)

library(stringi)

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


[1] "1.5L
MFR
  • 2,049
  • 3
  • 29
  • 53
0

This should work

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