user 32394023 user 32394023 - 1 year ago 86
Ruby Question

Split by multiple delimiters

I'm receiving a string that contains two numbers in a handful of different formats:

"344, 345"
"432 345"

I need to split them into two separate numbers in an array using
, and then convert them using

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 a space in the comma version shown above (
"344, 345"

How can I match multiple delimiters?

Answer Source

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)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download