4

I need to split a string without removing the separators. Is there a simple and "Ruby oriented" way to do this?

For example, given a string like this:

str = "(This is (a test))"

what I need is this:

["(", "This", "is", "(", "a", "test", ")", ")"]

I tried using the split method for strings, using the brackets "(" and ")" as separators, but then I get them removed from the returning array. Any advice will be helpful.

4
  • What happened to the spaces in your original string? They aren't present in the array of strings. Commented Apr 6, 2012 at 15:18
  • I wish them to be removed from the array. Commented Apr 6, 2012 at 15:20
  • 2
    This looks more like a token parsing problem... Commented Apr 6, 2012 at 15:20
  • Yes: I'm trying to figure out how to acquire a string in a binary tree, in a lisp-like way, saving the words in the leaves. To do this (not sure if the best way to do so) I need to solve this problem. Commented Apr 6, 2012 at 15:25

1 Answer 1

8

Maybe something like this:

str.scan(/\(|\)|\w+/)
Sign up to request clarification or add additional context in comments.

2 Comments

This regexp will ignore all other characters. Is that what you want?
Good but just slightly cleaner is: /[()]|\w+/

Your Answer

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.