From: "Aleksi Niemelä" Date: 2000-11-07T13:37:29+09:00 Subject: [ruby-talk:6101] RE: Regex question -- new("") vs. // Dear Hal, > Why are these three patterns below not the same? It's a little bit hard to tell exactly what's going on, as I'm not sure where you target. The thing here is that you have to be careful what you pass around. So Regexp.new(/doesn't need escaping backslashes for digit \d/) but Regexp.new("does need, and \d translates to plain d") before passing a string to constructor so the backslash flattens out. That means you have to say Regexp.new("\\d") to say same as Regexp.new(/\d/) or shorter /\d/. There are other quirks around too, so beware, and test throughtly before assuming the Regexp works. But here's briefly rewritten version of your test program. And after that the output it generates. - Aleksi regexps = [ Regexp.new("^(\d[\d_]*)*\.[\d_]*"), /^(\d[\d_]*)*\.[\d_]*/, Regexp.new("^(\\d[\\d_]*)*\.[\\d_]*"), # these three are equal, note I changed one '*' to '?' Regexp.new("^(\\d[\\d_]*)?\\.[\\d_]*"), Regexp.new(/^(\d[\d_]*)?\.[\d_]*/), /^(\d[\d_]*)?\.[\d_]*/, ] tests = [ "_123.45", "1_234.56"] tests.each do |test| puts "Testing: '#{test}'" regexps.each_with_index do |re, i| print "#{i+1}: #{re.inspect}, " if re.match( test ) print "\tyes ('#{$&}')" else print "\tno" end puts end puts end And the output: Testing: '_123.45' 1: /^(d[d_]*)*.[d_]*/, yes ('_') 2: /^(\d[\d_]*)*\.[\d_]*/, no 3: /^(\d[\d_]*)*.[\d_]*/, yes ('_123') 4: /^(\d[\d_]*)?\.[\d_]*/, no 5: /^(\d[\d_]*)?\.[\d_]*/, no 6: /^(\d[\d_]*)?\.[\d_]*/, no Testing: '1_234.56' 1: /^(d[d_]*)*.[d_]*/, yes ('1_') 2: /^(\d[\d_]*)*\.[\d_]*/, yes ('1_234.56') 3: /^(\d[\d_]*)*.[\d_]*/, yes ('1_234.56') 4: /^(\d[\d_]*)?\.[\d_]*/, yes ('1_234.56') 5: /^(\d[\d_]*)?\.[\d_]*/, yes ('1_234.56') 6: /^(\d[\d_]*)?\.[\d_]*/, yes ('1_234.56')