Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby Regex - Need to replace every occurrence of a character inside a regex match

Here's my string:

mystring = %Q{object1="this is, a testyay', asdkf'asfkd", object2="yo ho', ho"}

I am going to split mystring on commas, therefore I want to (temporarily) sub out the commas that lie in between the escaped quotes.

So, I need to match escaped quote + some characters + one or more commas + escaped quote and then gsub the commas in the matched string.

The regex for gsub I came up with is /(".*?),(.*?")/, and I used it like so: newstring = mystring.gsub(/(".*?),(.*?")/ , "\\1|TEMPSUBSTITUTESTRING|\\2"), but this only replaces the first comma it finds between the escaped quotes.

How can I make it replace all the commas?

Thanks.

like image 976
johnnycakes Avatar asked Dec 03 '25 18:12

johnnycakes


2 Answers

I believe this is one way to achieve the results you are wanting.

newstring = mystring.gsub(/".*?,.*?"/) {|s|  s.gsub( ",", "|TEMPSUBSTITUTESTRING|" ) }

It passes the matched string (the quoted part) to the code block which then replaces all of the occurrences of the comma. The initial regex could probably be /".*?"/, but it would likely be less efficient since the code block would be invoked for each quoted string even if it did not have a comma.

like image 170
Mark Wilkins Avatar answered Dec 06 '25 08:12

Mark Wilkins


Don't bother with all that, just split mystring on this regex:

,(?=(?:[^"]*"[^"]*")*[^"]*$)

The lookahead asserts that the comma is followed by an even number of quotes, meaning it's not inside a quoted value.

like image 27
Alan Moore Avatar answered Dec 06 '25 08:12

Alan Moore



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!