Maksym Popov
Maksym Popov

Reputation: 452

How to split string in correct way?

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?

Upvotes: 2

Views: 51

Answers (1)

trincot
trincot

Reputation: 351183

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+@)/)

Upvotes: 5

Related Questions