How to replace a special character between words in R

I have a character string.

str = c(".wow", "if.", "not.confident", "wonder", "have.difficulty", "shower")

I'm trying to replace the "." between words with a space. So it will look like

".wow", "if.", "not confident", "wonder", "have difficulty", "shower"

I tried first

gsub("[\\w.\\w]", " ", str)
[1] "  o "            "if"              "not confident"   " onder"         
[5] "have difficulty" "sho er " 

He gave me the spaces that I want, but chopped off all w. Then i tried

gsub("\\w\\.\\w", " ", str)
[1] ".wow"          "if"            "no onfident"   "wonder"       
[5] "hav ifficulty" "shower."    

He saved w, but removed other characters right before and after the "." .

I can not use this either

gsub("\\.", " ", str)
[1] " wow"             "if "              "not.confident"   "wonder"         
[5] "have.difficulty" "shower" 

because it will take "." not between words.

+2
source share
2 answers

Try

gsub('(\\w)\\.(\\w)', '\\1 \\2', str)
#[1] ".wow"            "if."             "not confident"   "wonder"         
#[5] "have difficulty" "shower"       

or

gsub('(?<=[^.])[.](?=[^.])', ' ', str, perl=TRUE)

Or as @rawr suggested

gsub('\\b\\.\\b', ' ', str, perl = TRUE)
+2
source

Using capture groups and backlinks :

sub('(\\w)\\.(\\w)', '\\1 \\2', str)
# [1] ".wow"            "if."             "not confident"   "wonder"         
# [5] "have difficulty" "shower"

( ... ). Backreferences , .

(\); , .

lookaround :

- . "" .

sub('(?<=\\w)\\.(?=\\w)', ' ', str, perl = TRUE)
+4

All Articles