Split string into array with regex but without removing the matches

338 views Asked by At

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

1

There are 1 answers

3
Jonne Haß On BEST ANSWER

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"]