2

How can I remove space before and after @?

For example,

safety@ gmail.com / ghjv@gmail.com
gjhv_mf6 @ hotmail.com,hhty @gmail.com

the desired output will be:

safety@gmail.com / ghjv@gmail.com
gjhv_mf6@hotmail.com,hhty@gmail.com
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
user3642360
  • 762
  • 10
  • 23

2 Answers2

3

gsub() should do it.

string_vec <- c("safety@ gmail.com / ghjv@gmail.com",
            "gjhv_mf6 @ hotmail.com,hhty @gmail.com")
gsub(" *@ *","@",string_vec)

If you want to remove all whitespace (including tabs etc.), follow this question:

gsub("[[:space:]]*@[[:space:]]*", "@", string_vec) 
Ben Bolker
  • 211,554
  • 25
  • 370
  • 453
1

Another option it to remove optional whitespace before and after "@".

Using @BenBolker's data

gsub("\\s?@\\s?", "@", string_vec)
#[1] "safety@gmail.com / ghjv@gmail.com"   "gjhv_mf6@hotmail.com,hhty@gmail.com"

OR with stringr::str_replace_all

stringr::str_replace_all(string_vec, "\\s?@\\s?", "@")
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
  • FWIW `?` (instead of `*`) will match only 0 or 1 instances of whitespace -- won't match many spaces in a row (but we don't know what the OP wants) – Ben Bolker Apr 25 '19 at 02:18