Search code examples
crystal-lang

Split string into array with regex but without removing the matches


In python I can do:

import re

re.split('(o)', 'hello world')

and get:

['hell', 'o', ' w', 'o', 'rld']

With crystal:

"hello world".split(/(o)/)

I get:

["hell", " w", "rld"]

But I want to keep the matches in the array like in the python example. Is it possible?

http://crystal-lang.org/api/String.html


Solution

  • This just got added, see this issue.

    Until that lands in a release you can trick with lookaround expressions:

    "hello world".split(/(?<=o)|(?=o)/) #=> ["hell", "o", " w", "o", "rld"]