Ruby RegEx not matching valid expression
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 aEverything works, but when I use it in Ruby it does not work!
expressio开发者_开发技巧n =~ /^\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 correctWhy is this expression not working in Ruby code? (I am using Ruby 1.8.7 p174)
This should work: /^(\w+)(?:\s*(\+|\-|\*|\/)\s*(\w+))*$/
I added some captures for backreferencing
You might try:
/^\w(\s(\+|-|\/|\*)\s\w)*$/
This works for me in irb:
expression =~ /^\w(\s(\+|-|\/|\*)\s\w)*$/
I tested it with your terms:
irb(main):019:0> expressions = ["a + a", "a + a + a", "a + a +",
"a +", "a a", "a + a a"]
=> ["a + a", "a + a + a", "a + a +", "a +", "a a", "a + a a"]
irb(main):023:0> expressions.each { |expression|
irb(main):024:1* puts expression =~ /^\w(\s(\+|-|\/|\*)\s\w)*$/
irb(main):025:1> }
0
0
nil
nil
nil
nil
I should be using \w+ as I can recieved terms of more than one character...
^\w+(\s(+|-|/|)\s\w+)$
Thanks for the responses everyone.
精彩评论