From: Daniel N Date: 2006-08-08T18:37:03+09:00 Subject: Re: value of $1is retained ------=_Part_4664_3012933.1155029819337 Content-Type: text/plain; charset=ISO-8859-1; format=flowed Content-Transfer-Encoding: 7bit Content-Disposition: inline On 8/8/06, Anders Vesterberg wrote: > > Hi > I am using regexp in a loop to extract a value from a > string. I have noticed that when string is nil $1 keeps its > old value, which means that the expression after regexp > does not get the correct value (which should be nil). The > code looks like this > > (0..key_colnames.length-1).each do |i| > person_data[key_colnames[i]] =~ /\"?([\w\-: ]*)\"?/ > # assigning $1 to something > end > > Shouldn't the $-variables be reset after each regexp? Or is > it a better way to do this? > > /Anders Vesterberg > http://www.vesterberg.se The problem is in your regex. It will match a word containing hyphens or : but it will also match an empty string! >> a = /\"?([\w\-:]*)\"?/ => /\"?([\w\-:]*)\"?/ >> "This is a String" =~ a => 0 >> $1 => "This" >> "" =~ a => 0 >> $1 => "" >> "$12dc" =~ a => 0 >> $1 => "" Without knowing very much about the requirements of your regex, you need to replace the * wildcard ( zero or more ) with + (one or more) >> a = /\"?([\w\-:]+)\"?/ => /\"?([\w\-:]+)\"?/ >> "This is a String" =~ a => 0 >> $1 => "This" >> "" =~ a => nil >> $1 => nil >> "$12dc" =~ a => 1 >> $1 => "12dc" Nils as you would expect. You could also make the first line it a touch more rubyish ;) key_colnames.each do |key| person_data[key] =~ /\"?([\w\-:])\"/ # do your thing with $1 end ------=_Part_4664_3012933.1155029819337--