tags:

views:

80

answers:

5

I want to match strings like this: !! so I suppose the input have the right elements but whether the they are evaluable, that is left for the evaluator!

1+(2-3)*(4/5)

what is the regex for matching this, something like this: ([0-9\+-\*\/\(\)]+)? but this seems not working.

+1  A: 

Regular expressions can not match arbitrary arithmetic formulas. Regexps only describe regular languages, while arithmetic formulas use a recursive grammar. See http://en.wikipedia.org/wiki/Regular_expression#Formal_language_theory

A regex may be possible if you limit nesting depth, but if you want it all the way, with matching bracket detection, it will probably be very, very complicated.

Gintautas Miliauskas
so I suppose the input has the right elements but whether the they are evaluable, that is left for the evaluator!
baboonWorksFine
+1  A: 

You can't, this is not a regular language. Though some regexp implementations may provide additional features to match balanced parenthesis.

rkhayrov
+1  A: 

If you are only asking for a character validation, you can use

^[0-9+*/()-]*$

You don't need to escape characters in a character class (inside square brackets). And if you must include an hyphen, you HAVE to put it at the end, otherwise it would be considered as the character range operator.

That said, keep in mind this will only guarantee you that you have no other characters. It will NOT validate the structure (regexes are not the right tool for that). However, since you stated an evaluator will then process the input, that might be right for you.

Guillaume Bodi
A: 

If you want to match "1+(2-3)*(4/5)", then you can use this regular expression.

/1+\(2-3\)\*\(4\/5)/

What's that? That doesn't tell you what you want to know? Well, then what do you want to know? What information are you trying to extract from the string?

You can't just say "strings like this". Your question is not nearly enough clear.

Andy Lester
A: 

If your question is to evaluate if a equation is valid then you will need a parser to Tokenize the expression than a grammar to evaluate if the expression is right.

You cant check if the equation as balanced parenthesis using regex. This is because a regular expression is equivalent to a Deterministic Finite Automata. Since the automata is finite, you will never have a automata big enough to check parenthesis.

Guillaume Massé