2

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?

asked Oct 22, 2020 at 15:29
0

1 Answer 1

5

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+@)/)
answered Oct 22, 2020 at 15:32
Sign up to request clarification or add additional context in comments.

1 Comment

OP: And for what it's worth, there's no need to escape @ in regular expressions.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.