Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split String without removing separator in Elixir?

I'm looking for a way to split a string in Elixir without removing the pattern used to split, String.split/3 behaves like this

String.split "testZng", "Z"
# ["test", "ng"]

I'm looking for something like this

String.split "testZng", "Z"
# ["test", "Zng"]

Or like this

String.split "testZng", "Z"
# ["testZ", "ng"]
like image 566
gmelodie Avatar asked Nov 16 '25 05:11

gmelodie


1 Answers

You may use lookarounds:

Regex.split ~r/(?=Z)/, "testZng"
# ["test", "Zng"]

Regex.split ~r/(?<=Z)/, "testZng"
# ["testZ", "ng"]

The (?=Z) is a positive lookahead that matches a location in the string that is immediately followed with a Z char.

The (?<=Z) is a positive lookbehind that matches a location in the string that is immediately preceded with Z.

like image 63
Wiktor Stribiżew Avatar answered Nov 17 '25 21:11

Wiktor Stribiżew



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!