From: Robert Klemme Date: 2010-02-27T06:57:54+09:00 Subject: Re: Regex for "not matching" an unneeded prefix substring? 2010/2/26 Jet Koten : > Hi all, > > I'm new to Ruby and even newer to regex. I'm trying to write my first > [useful] Ruby program and need a way to cut out an unneeded prefix > substring and retain the substring that comes after it. > > Here are the actual details from my code: > > result.each do |item| >  price = item.search(".price").text.match(/\d+[.]\d+/) >  condition = item.search(".condition").text.match(/Used - ([^,]+)/) >  rating = item.search(".rating a").text.to_i >  seller = item.search(".seller b").text >  puts "#{price} - #{condition} - #{rating} - #{seller}" > end > > The one from condition [in the code above] is the one that is giving me > a challenge. The string that is sent to condition will always be exactly > one of the following and nothing else at all: > > "Used - Like New" > "Used - Very Good" > "Used - Good" > "Used - Acceptable" > > I'm trying to get them to display as the following in the puts at the > end of my code: > > "Like New" > "Very Good" > "Good" > "Acceptable" > > The regex that I've got there in the condition line works in Rubular, > but not in my code. I'm running 1.8.7 if that matters... I am not sure which regexp you are referring to specifically. However, you can do this irb(main):001:0> s = "Used - Like New" => "Used - Like New" irb(main):002:0> s[/\AUsed\s+-\s+(.*)\z/, 1] => "Like New" irb(main):003:0> s[7..-1] => "Like New" String#[] with regular expression is a very powerful tool - especially when used with grouping as in this case. > One last thing that I don't understand too is that in Rubular my regex > for price shows the match in the "Match result:" line, but the regex for > condition shows the whole string as a match in the "Match result:" line > but shows the correctlt matching substring in the "Match captures:" > line. I am having difficulties to follow you here since I don't know what "item" is in your case. It's probably easier if you provide a simple test case that demonstrates your point. Using IRB often also helps. > I'm grateful for this great resource (the list/forum) and would be very > happy to hear from anyone who can help me sort this out! We'll try to help but please provide a bit more information. Kind regards robert -- remember.guy do |as, often| as.you_can - without end http://blog.rubybestpractices.com/