user 32394023 user 32394023 - 6 months ago 51
Ruby Question

Ruby - split by multiple delimiters

I'm receiving a string that contains two numbers and it can be received in a handful of different formats.

"344, 345"
,
"334,433"
, "
345x532"
and
"432 345"


I need to split these into two separate numbers inside an array using
split()
, and then converting using
Integer(num)
.

What I've tried so far:

nums.split(/[\s+,x]/) # split on one or more spaces, a comma or x


However, it doesn't seem to match multiple spaces when testing - also, it doesn't allow for the space in the comma version shown above (
"344, 345"
).

How can I match multiple delimiters in Ruby? Thank you

Answer

You are using a character class in your pattern, and it matches only one character. [\s+,x] matches 1 whitespace, or a +, , or x. You meant to use (?:\s+|x).

However, perhaps, a mere \D+ (1 or more non-digit characters) should suffice:

"345, 456".split(/\D+/).map(&:to_i)