Eyayaw
Eyayaw

Reputation: 1081

How to insert separator (comma) in a character?

How can I change @ManuelaSchwesig@sigmargabriel@nahles into @ManuelaSchwesig, @sigmargabriel, @nahles using R?

Upvotes: 1

Views: 845

Answers (1)

akrun
akrun

Reputation: 887173

We could try with a regex lookaround by splitting at the junction of a lower case letter and the @ character to create a vector of strings. Here, the pattern for strsplit is a positive regex lookbehind ((?<=[a-z])) followed by a positive regex lookahead ((?=@)). In the string, there are two instances where it matches i.e. between g and @ (Schweig@sigma) and l and @ in (gabriel@nahles) and splits between these characters

strsplit(str1, "(?<=[a-z])(?=@)", perl = TRUE)[[1]]
#[1] "@ManuelaSchwesig" "@sigmargabriel"   "@nahles" 

If we need to keep it as a single string and the objective is to insert a ,

gsub("([a-z])@", "\\1,@", str1)
#[1] "@ManuelaSchwesig,@sigmargabriel,@nahles"

data

str1 <-  "@ManuelaSchwesig@sigmargabriel@nahles"

Upvotes: 2

Related Questions