Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby regexp to match comma, but ignore comma in brackets

Tags:

regex

ruby

I'm trying to split a parameter list by regexp.

This is a string with my parameter list:

"a = b, c = 3, d = [1,3,5,7], e, f = g"

What I want is:

["a = b", "c = 3", "d = [1,3,5,7]", "e", "f = g"]

I tried with a lookahead, but Ruby doesn't allow lookbehinds with a dynamic range, so this won't work:

/(?<!\[),(?!\w*\])/

How can I tell the regexp to ignore everything in square brackets?

like image 553
Kurt Avatar asked Jun 20 '13 15:06

Kurt


2 Answers

Maybe something like that would work for you:

 str.scan(/(?:\[.*?\]|[^,])+/)

EDIT after second thought.

Simple non-greedy matcher will fail in some cases of nested parentheses.

like image 75
samuil Avatar answered Sep 28 '22 06:09

samuil


Rather than trying to get it all done with one splitting regex, you could split, then correct your array of pairs.

input = "a = b, c = 3, d = [1,5], e = f"
pairs = input.split(/,\s*/)
pairs.each_with_index do |item, index|
  if index > 0 && (item =~ /=/).nil?
    pairs[index - 1] += ',' + item
    pairs[index] = nil
  end
end
pairs.delete_if { |item| item.nil? }
puts pairs

Outputs:

a = b
c = 3
d = [1,5]
e = f
like image 45
jimbo Avatar answered Sep 28 '22 06:09

jimbo