How to replace a space with a semicolon between two words with gsub ()

2

I have a problem to solve and I can not write the correct regex. I want to add a semicolon between two emails:

ex <- "[email protected] [email protected]"

#resultado esperado:
[1] "[email protected];[email protected]"

Thanks for the help!

    
asked by anonymous 26.07.2018 / 22:00

2 answers

5

Here it goes:

ex <- "[email protected] [email protected]"

# Com o gsub()
gsub(pattern = "[[:blank:]]",
     replacement = ";",
     x =  ex)

# Com str_replace_all(), que eu prefiro
library(stringr)
str_replace_all(string = ex,
                pattern = "[[:blank:]]",
                replacement = ";")

You could also do this:

str_replace_all(string = ex,
                pattern = "[ ]",
                replacement = ";")

Or else this:

str_replace_all(string = ex,
                pattern = "[[:space:] ]",
                replacement = ";")

[[:blank:]] works to eliminate all types of white space, including tabs, etc. With [ ] (a space between brackets) you only remove the same common space. And with [[:space:]] it is possible to eliminate spaces, tabs and also line breaks.

    
26.07.2018 / 22:46
-1

Another simpler option would be:

ex <- "[email protected] [email protected]"

new_ex <- gsub(" ", ";", ex)

new_ex
    
17.09.2018 / 09:43