Feng Chen
Feng Chen

Reputation: 2253

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

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

Answers (3)

akrun
akrun

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"

data

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

Upvotes: 1

Vishal Jaiswal
Vishal Jaiswal

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

MFR
MFR

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

Related Questions