简体   繁体   English

条件运算符的 C# 正则表达式示例 eq:2 , ne:3

[英]C# regex for conditional operators example eq:2 , ne:3

I wanted to write an regex in C# for strings which can comprise of any operator and operand value.我想在 C# 中为可以包含任何运算符和操作数值的字符串编写一个正则表达式。 These operators are string characters like eq for equals , ct = contains & bt for between , eq for equals.这些运算符是字符串字符,例如 eq 表示相等,ct = contains & bt 表示 between ,eq 表示相等。

i get strings into backend like eq=4.我将字符串放入后端,如 eq=4。 But during test someone tested my code with garbage values to my API and the string was eq:**+4.但是在测试过程中,有人用垃圾值测试了我的代码到我的 API 并且字符串是 eq:**+4。

Now i want to build an regex such that it will validate string against regex values like eq:5 or bt:8-9.现在我想构建一个正则表达式,以便它根据 eq:5 或 bt:8-9 等正则表达式值验证字符串。

JUST A NOTE : exlcuding between operator no other operator should have such value like eq:4-6.请注意:在操作员之间排除其他操作员不应该具有像 eq:4-6 这样的值。

i have done this @"^\\b(eq | ne | gt | lt | ge | le | ct | bt)\\w\\b : ? (\\d | - ) ? \\d"我已经这样做了@"^\\b(eq | ne | gt | lt | ge | le | ct | bt)\\w\\b : ? (\\d | - ) ? \\d"

seems im close but need some guidance to get this properly working.似乎我很接近,但需要一些指导才能使其正常工作。

Any help or suggestion is welcome.欢迎任何帮助或建议。

(eq|ne|gt|lt|ge|le|ct|bt):-?[0-9]+(--?[0-9]+)?

or with named group: @"(?<operator>eq|ne|gt|lt|ge|le|ct|bt):(?<firstValue>-?[0-9]+)(-(?<secondValue>-?[0-9]+))?$"或命名组: @"(?<operator>eq|ne|gt|lt|ge|le|ct|bt):(?<firstValue>-?[0-9]+)(-(?<secondValue>-?[0-9]+))?$"

demo : https://regex101.com/r/HWnIq9/1演示: https : //regex101.com/r/HWnIq9/1

You can use您可以使用

@"^(eq|[gln]e|[bclg]t)\s*:\s*\d+(?:\.\d+)?(?:-\d+(?:\.\d+)?)?\z"

See the regex demo .请参阅正则表达式演示 Details :详情

  • ^ - start of string ^ - 字符串的开始
  • (eq|[gln]e|[bclg]t)
  • \\s*:\\s* - a colon enclosed with zero or more whitespaces \\s*:\\s* - 用零个或多个空格括起来的冒号
  • \\d+(?:\\.\\d+)? - an int/float number (one or more digits and then an optional sequence of a dot and one or more digits) - 一个整数/浮点数(一个或多个数字,然后是一个点和一个或多个数字的可选序列)
  • (?:-\\d+(?:\\.\\d+)?)? - an optional sequence of a - , one or more digits and then an optional sequence of a dot and one or more digits -一个可选的序列-一个或多个数字,然后一个点的可选序列和一个或多个数字
  • \\z - the very end of string. \\z - 字符串的末尾。

See the difference between $ and \\z anchors in .NET regex.查看 .NET 正则表达式中$\\z锚点之间区别

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

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