Ruby RegEx not matching valid expression
- by Matthew Carriere
I have the following expression:
^\w(\s(+|-|\/|*)\s\w)*$
This simply looks to match a mathematical expression, where a user is prompted for terms separated by basic operators (ex: price + tax)
The user may enter more than just 2 terms and one operator (ex: price + tax + moretax)
I tested this expression in Rubular http://rubular.com/
With the terms:
a + a (MATCH)
a + a + a (MATCH)
a + a +
a +
a a
a + a a
Everything works, but when I use it in Ruby it does not work!
expression =~ /^\w(\s(+|-|\/|*)\s\w)*$/
I started picking the expression apart and noticed that if I remove the start of line caret it finds matches but isn't correct.
a + a (MATCH)
a a (MATCH) <-- this is not correct
Why is this expression not working in Ruby code? (I am using Ruby 1.8.7 p174)