1

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 ?

3
  • Show us of examples where it gives unexpected results. Commented Dec 9, 2013 at 10:22
  • Seems to be no apparent method to what you want and not ... is just the order of the operands that decides if it's ok or not ? Commented Dec 9, 2013 at 10:41
  • @Noctis, Yes you got it right. Commented Dec 9, 2013 at 10:43

3 Answers 3

3

Your regex should be

^(\(?\d+\)?|\(?[$][^$]+[$]\)?)([+*/-](\(?\d+\)?|\(?[$][^$]+[$]\)?))*$
 ----------------------------- --------------------------------------
         |                     ------        |->matches 0 to many operands on right                   |
         |                       |
         |                       |->matches operator +,-,*,/
         |->Matches an operand(digit or named variable) on left
Sign up to request clarification or add additional context in comments.

2 Comments

Nice one. However, maybe this [^$]+ should be replaced by [a-z|A-Z] as given by the author? Otherwise variables like $%#*$ will pass.
@gehho , do not worry these kind of variables wont pass as the vriables are selected from a combobox.Anirudh +1
0

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 :)

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.