How to split string in correct way?

Viewed 45

For example, I have this string:

a = "Hello, @USER_ID:1@, how are you?"

I need to turn this string into array of words:

["Hello, ", "@USER_ID:1@", ", how are you?"]

I've tried this piece of code:

a.split(/\@USER_ID:([0-9]+)\@/)

But it returns this:

 ["Hello, ", "1", ", how are you?"]

What is the proper way to split this string?

1 Answers

If you use a regular expression as split argument, the capture group (matched by what is between parentheses) is also returned in the result. So you should just make that capture group the whole expression:

 a.split(/(\@USER_ID:[0-9]+\@)/)

Note that the regular expression can be shortened to:

 a.split(/(@USER_ID:\d+@)/)
Related