Home > Blockchain >  Replace the dot at the end of a string in R
Replace the dot at the end of a string in R

Time:12-31

Here is a string.

"DEL.Xp22.11..ZFX." 

I want to replace the .. with a space and a left parenthesis ( and the last . with a right parenthesis ).

"DEL.Xp22.11 (ZFX)" 

I tried the following to replace the double dots while I dont know how to replace the last dot.

gsub("..", ' (', "DEL.Xp22.11..ZFX.", fixed = T)

[1] "DEL.Xp22.11 (ZFX."

CodePudding user response:

Try :

x <- "DEL.Xp22.11..ZFX."
x <- gsub("..", ' (', x, fixed = T)
x <- gsub("\\.$", ')', x)

Here I use the regex anchor '$' to signify the end of the word. And '\' to escape the '.' that is a regex special character.

CodePudding user response:

You need to use the following regex-based solution:

sub("\\.{2}([^.] )\\.$", "(\\1)", x)

See the regex demo. Details:

  • \.{2} - two dots
  • ([^.] ) - Group 1 (\1 refers to this value from the replacement pattern): one or more chars other than a . char
  • \. - a single dot
  • $ - end of string.

See the R demo online:

x <- "DEL.Xp22.11..ZFX."
sub("\\.{2}([^.] )\\.$", "(\\1)", x)
# => [1] "DEL.Xp22.11(ZFX)"
  • Related