简体   繁体   English

使用正则表达式验证字符串

[英]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$ 注意: $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). 这将是容易更换您的$operand_name$X的验证方法(字符串替换例如)和简单地比较针对(所以X+3是确定的和3+X不是)。

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 :) 否则,我看到Anirudh有一个很好的正则表达式,你可以用它来捕杀,但我不想成为一个维护代码,也不想尝试添加新的规则:)

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. 你应该有一些COTS。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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