Reputation: 2253
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?
Upvotes: 1
Views: 237
Reputation: 887153
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"
str1 <- c("xxxxxx xxxx xxxxxx 1.5L xxxxx" , "xxxxxx xxxx xxxxxx 1.5 L xxxxx")
Upvotes: 1
Reputation: 144
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))
}
Upvotes: 0
Reputation: 2077
We can use library(stringi)
library(stringi)
text <- "1.5 L"
stri_replace_all(text,"1.5L" ,fixed = "1.5 L" )
[1] "1.5L
Upvotes: 0