简体   繁体   中英

Difference in regex between Rails and Ruby?

I am attempting to match a value like 'MN+WI' at the end of a URL, for example /foos/MN+WI . The pattern [a-zA-Z][\\+\\,]? produces a match result of MN+WI on rubular.com, but in IRB:

s="MI+WI"
p="[a-zA-Z]{2}[\+\,]?"
r=Regexp.new(p)
r.match(s) # => #<MatchData "MI+"> 

The behavior in Ruby console is consistent with what I am encountering with Rails. Is there a difference between the two? How do I need to adjust my regex pattern?

$ ruby -v
ruby 2.0.0p247 (2013-06-27 revision 41674) [x86_64-darwin12.3.0]

$ rails -v
Rails 4.0.0

** edit **

Original pattern should have been [a-zA-Z]{2}[\\+\\,]? .

What I really need to have a route recognize any of these variations and assign it to a param:

  • MN (working)
  • mn (working)
  • MN+WI (not working)
  • MN+WI+IA (arbitrary number of 2-letter value, separated by a + )
  • not match single or more than 2-letter values (eg ABC ), but keep 2-letter values (eg ABC+MN ; keep MN )

As I said in my comment, [a-zA-Z][\\+\\,]? does not match MN+WI. What you are seeing on Rubular is actually two matches. The first match is MN+ , and the second match WI . Rubular just highlights all the matches, so it looks like one long match but it is actually two matches. The behavior should be consistent between Rubular and your local Ruby install.

Your regexp means "2 letters followed by optional + or ,". So your string has 2 matches. Rubular highlights all matches, and it looks like the whole string is matched, but in reality there are 2 different matches = MN+ and WI

Rubular is showing the result of the repeated application of the pattern:

[a-zA-Z][\+\,]?

If you put that pattern in a capture group, you'll see each of the individual matches (see http://rubular.com/r/h5iBa5k0fr ), each of which matches a single character except for N+ .

Your IRB code returns a single match. Note also, though, that your IRB code is different than the above regex due to your inclusion of {2} .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM