Is there a different way to replace these brackets using Ruby regex? -



Is there a different way to replace these brackets using Ruby regex? -

i have string contains 2-d array.

b= "[[1, 2, 3], [4, 5, 6]]" c = b.gsub(/(\[\[)/,"[").gsub(/(\]\])/,"]")

the above how decide flatten to:

"[1, 2, 3], [4, 5, 6]"

is there way replace leftmost , rightmost brackets without doing double gsub call? i'm doing deeper dive regular expressions , see different alternatives.

sometimes, string may in right format comma delimited 1-d arrays.

the gsub method accepts hash, , matches regular look replaced using keys/values in hash, so:

b = "[[1, 2, 3], [4, 5, 6]]" c = b.gsub(/\[\[|\]\]/, '[[' => '[', ']]' => ']')

that may little jumbled, , in practice i'd define list of swaps on different line. looking 1 gsub, in more intuitive way.

another alternative take advantage of fact gsub accepts block:

c = b.gsub(/\[\[|\]\]/){|matched_value| matched_value.first}

here match double opening/closing square brackets, , take first letter of matches. can clean regex:

c = b.gsub(/\[{2}|\]{2}/){|matched_value| matched_value.first}

this more succinct way specify want match 2 opening brackets, or 2 closing brackets. can refine block:

c = b.gsub(/\[{2}|\]{2}/, &:first)

here we're using ruby shorthand. if need phone call simple method on object passed block, can utilize &: notation this. think i've gotten short , sweetness can. happy coding!

ruby regex

Comments

Popular posts from this blog

Delphi change the assembly code of a running process -

json - Hibernate and Jackson (java.lang.IllegalStateException: Cannot call sendError() after the response has been committed) -

C++ 11 "class" keyword -