Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split by multiple delimiters

Tags:

string

regex

ruby

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

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

I need to split them into two separate numbers in an array using split, and then convert them 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 a space in the comma version shown above ("344, 345").

How can I match multiple delimiters?


2 Answers

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)
like image 142
Wiktor Stribiżew Avatar answered Aug 05 '26 13:08

Wiktor Stribiżew


R1 = Regexp.union([", ", ",", "x", " "])
  #=> /,\ |,|x|\ /
R2 = /\A\d+#{R1}\d+\z/
  #=> /\A\d+(?-mix:,\ |,|x|\ )\d+\z/

def split_it(s)
  return nil unless s =~ R2
  s.split(R1).map(&:to_i)
end

split_it("344, 345") #=> [344, 345] 
split_it("334,433")  #=> [334, 433] 
split_it("345x532")  #=> [345, 532] 
split_it("432 345")  #=> [432, 345] 
split_it("432&345")  #=> nil
split_it("x32 345")  #=> nil
like image 34
Cary Swoveland Avatar answered Aug 05 '26 12:08

Cary Swoveland



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!