Mike Mike - 11 months ago 41
Ruby Question

Why is my expression matching something that clearly doesn't meet the expression?

I'm using Rails 4.2.7. I want to match the pattern, numbers, an arbitrary number of spaces, and a potential "+" at the end. So I wrote

2.3.0 :013 > /\d+\s*\+?/.match("40+")
=> #<MatchData "40+">

However, this is also matching

2.3.0 :012 > /\d+\s*\+?/.match("40-50")
=> #<MatchData "40">

What gives? The string "40-50" doesn't match the expression provided, but clearly I'm not doing something right in my regex.

Answer Source

If you want it to match only the full string, use the \A and \z markers. Like this:


This will force the regular expression to match only if the full string match it.

Otherwise, the way you have it now, it will stop as soon as it find a match anywhere in your string.

\d+ means one digit or more.

\s* means an optional space.

\+? means an optional + sign

So 40 does match those conditions.