tags:

views:

49

answers:

4

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)

A: 

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
Firas Assaad
The light went on when I saw this test... I am testing with single characters but I am receiving words. I should be using \w+
Matthew Carriere
A: 

This should work: /^(\w+)(?:\s*(\+|\-|\*|\/)\s*(\w+))*$/ I added some captures for backreferencing

SHiNKiROU
A: 

You might try:

/^\w(\s(\+|-|\/|\*)\s\w)*$/
A: 

I should be using \w+ as I can recieved terms of more than one character...

^\w+(\s(+|-|\/|)\s\w+)$

Thanks for the responses everyone.

Matthew Carriere
You'll still get an error because you're not escaping + and *. ^\w+(\s(\+|-|\/|\\*)\s\w+)$ perhaps?
Firas Assaad