简体   繁体   中英

Validating a String using regex

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 (ie 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 ?

Your regex should be

^(\(?\d+\)?|\(?[$][^$]+[$]\)?)([+*/-](\(?\d+\)?|\(?[$][^$]+[$]\)?))*$
 ----------------------------- --------------------------------------
         |                     ------        |->matches 0 to many operands on right                   |
         |                       |
         |                       |->matches operator +,-,*,/
         |->Matches an operand(digit or named variable) on left

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM