'Ruby split string and preserve separator

In Ruby, what's the easiest way to split a string in the following manner?

  • 'abc+def' should split to ['abc', '+', 'def']

  • 'abc\*def+eee' should split to ['abc', '\*', 'def', '+', 'eee']

  • 'ab/cd*de+df' should split to ['ab', '/', 'cd', '*', 'de', '+', 'df']

The idea is to split the string about these symbols: ['-', '+', '*', '/'] and also save those symbols in the result at appropriate locations.



Solution 1:[1]

I see this is close to part of @naomic's answer, but I'll leave it for the small differences.

splitters = ['-', '+', '*', '/']

r = /(#{ Regexp.union(splitters) })/ 
  # => /((?-mix:\-|\+|\*|\/))/

'abc+def'.split r
  #=> ["abc", "+", "def"] 
"abc\*def+eee".split r
  #=> ["abc", "*", "def", "+", "eee"] 
'ab/cd*de+df'.split r
  #=> ["ab", "/", "cd", "*", "de", "+", "df"] 

Notes:

  • the regex places #{ Regexp.union(splitters) } in a capture group, causing String#split to include the strings that do the splitting (last sentence of the third paragraph).
  • the second example string must be in double quotes in order to escape *.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1