Reputation: 2256
I am trying to validate a user built query.
What I want to allow
$xxxx$+87*(50*2)
25*($total$-$absent$)
$total$+$present$
etc...
Note: $THESE_ARE_NAME_OF_OPERANDS$
What I do not want
$myoperand$+65io
ti88+$myoperand$
7kio07 + $operand$
etc...
Till now I tried to detect the bad combinations (i.e. combination of numbers and alphabets) using
var troublePattern = new Regex(@"\b[0-9]+[a-z|A-Z]");
string TroublePattern = troublePattern.ToString();
bool _present = Regex.IsMatch(UserFedData, TroublePattern, RegexOptions.None);
However it does not fully works. By fully works I mean it gives unexpected results at some point.
How do I have to modify my regex so as to acheive my aim ?
Upvotes: 1
Views: 108
Reputation: 739
What you are trying to do will be too complex to solve in a single regular expression. You will need to build a lexical analyzer to support all combinations of your query language.
It looks like that the query is some arithmetic syntax (basic math operations) using variables. There should be some COTS for you out there.
Upvotes: 0
Reputation: 11783
I would have tackle this with a combination of logic and regex.
Have a method that will check if the order of your operands is correct. It would be easy to replace your $operand_name$
with an X
in a validation method (string replace for example) and simply compare against that (so X+3
is ok and 3+X
is not).
Then you can use regex on the valid ones to your heart content.
Otherwise, I see Anirudh has a nice regex you can hunt a bear with , but I wouldn't want to be one maintaining that code, nor trying to add new rules to it :)
Upvotes: 0
Reputation: 32817
Your regex should be
^(\(?\d+\)?|\(?[$][^$]+[$]\)?)([+*/-](\(?\d+\)?|\(?[$][^$]+[$]\)?))*$
----------------------------- --------------------------------------
| ------ |->matches 0 to many operands on right |
| |
| |->matches operator +,-,*,/
|->Matches an operand(digit or named variable) on left
Upvotes: 3