From: 7stud -- Date: 2009-08-05T17:35:38+09:00 Subject: Re: remove commas from string Jason Lillywhite wrote: > I have following string: > > s = "B747-400, 8,357 miles, 561 mph, 4 Pratt & Whitney PW 4056 > turbofans, 56,000 lbs." > > I want to remove the comma only from the numbers (8,357 miles and 56,000 > lbs) separating the thousands. I want the string to read as follows: > > "B747-400, 8357 miles, 561 mph, 4 Pratt & Whitney PW 4056 turbofans, > 56000 lbs." > > I thought this following regex would do the trick because it > successfully isolated the right commas in rubular.com > > s.gsub(/\d+(,)\d+/, "") > > It turns out that my regex removes the entire number, not just the > comma. > > Am I wrong in saying that my regex searches for 1 or more numbers > surrounding a comma and replaces just the comma with ""? > Yes, you are wrong: s = "|yes|" puts s.gsub(/y(e)s/, "") --output:-- || gsub() replaces the whole match with the specified replacement. gsub() does not pick out a parenthesized group in the regex and replace that with the specified replacement . However, there is a block form of gsub: s = "yes, 1,234, yes, 4,567" result = s.gsub(/(\d),(\d)/) do |match| "#{$1}#{$2}" end puts result --output:-- yes, 1234, yes, 4567 Inside the block, $1, $2, $3, etc. refer to the matches for each parenthesized group in the regex. The return value of the block is used as the replacement. -- Posted via http://www.ruby-forum.com/.