[Quicky] Easy Ruby regexp to split string

Are you good at regexp? I'm not and I found an extremely easy way to update a regexp to split a string in Ruby.

Input

abc,abc
abc abc
abc

I just want to split on , , a space ... and a new line. Great

I won't show you an horrible .split with a .map then redo a .split again.

Use regexp

regexp = /[ ,\n]/
input.split(regexp)

It is annoying to read (even that simple) and it did not work for what I wanted. Remember the "new line", as a html input/textarea is not an \n but an \r\n .

You can change the regexp to /[ ,\r\n]/ but it split twice, once for \r then once more for \n. And the readability is lower.

Solution: Union!

regexp = Regexp.union([" ", "\r\n", "\n", ","])
input.split(regexp)

You give the string you want the regexp to split on and it generates the proper Regexp for you.

It won't solve all but for me, it solve most of my simple cases with code that I use everyday: a dead simple list of string.

Share it!

Cheers, Thomas

0
Subscribe to my newsletter

Read articles from Thomas Brennetot directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Thomas Brennetot
Thomas Brennetot

10+ years most with Ruby on Rails and JavaScript frontend and some Go. My first language is C for 3 years in university.