简体   繁体   English

如何为给定的例子制定正则表达式

[英]How to formulate Regular expression for given example

I'm not very well versed with regular expressions. 我对正则表达式并不十分熟悉。 I've had to use them, maybe once every few years, and that was mostly for course work. 我不得不使用它们,也许每隔几年使用一次,这主要是为了课程工作。 Anyways, the following question should be a fairly straight forward question/answer for anyone familiar with regular expressions. 无论如何,对于熟悉正则表达式的人来说,以下问题应该是一个相当直接的问题/答案。

I need to ensure that the text entered into a field follows the following format: 我需要确保输入字段的文本遵循以下格式:

x y z

or 要么

x,y,z

or 要么

x y z / <same pattern can repeat for almost unlimited length>

or 要么

x,y,z / <...> // Spaces after the comma are ok

where x, y and z can only be integers. 其中x,y和z只能是整数。 The patterns cannot be intermixed, so you cannot have 图案不能混合,所以你不能拥有

x, y, z / x y z / ...

I've tried the following 我尝试了以下内容

([1-9] [1-9] [1-9])

to get the xyz part, but I don't know how to include the '/' nor the ',' 获取xyz部分,但我不知道如何包含'/'和','

Any suggestions? 有什么建议么?

Try to break your regular expression down into pieces. 尝试将正则表达式分解成碎片。 Then try to combine them. 然后尝试将它们组合起来。

For example, an integer like 1024 is a sequence of one ore more digits, ie [0-9]+ . 例如,像1024这样的整数是一个或多个数字的序列,即[0-9]+ Etc. 等等。

Grammar: 语法:

digit     ::= [0-9]
space     ::= [ ]
slash     ::= [/]
comma     ::= [,]

integer   ::= digit+
separator ::= space | comma
group     ::= integer separator integer separator integer
group-sep ::= space slash space
groups    ::= group ( group-sep group )*

Regex: 正则表达式:

([0-9]+[ ,][0-9]+[ ,][0-9]+)([ ][/][ ][0-9]+[ ,][0-9]+[ ,][0-9]+)*

I guess you can use 我猜你可以用

Regex r = new Regex("^([0-9]+([ ,]|, )[0-9]+(\\2)[0-9]+)( [/] ([0-9]+(\\2)[0-9]+(\\2)[0-9]+)+)*$");

var x1 = r.IsMatch("1,2 3");         // false
var x2 = r.IsMatch("1 3 2 / 1 2 3"); // true
var x3 = r.IsMatch("1,3,2");         // true
var x4 = r.IsMatch("1 3 2 / 1");     // false

Console.WriteLine((x1 == false) ? "Correct" : "Error");
Console.WriteLine((x2 == true) ? "Correct" : "Error");
Console.WriteLine((x3 == true) ? "Correct" : "Error");
Console.WriteLine((x4 == false) ? "Correct" : "Error");
Console.ReadLine();

Spliting in smaller pieces 分成小块

[0-9]+  matches any number, even 0. If it can't start with 0
        you will have to change it
[ ,]    the separator allows a space or a comma
\\2     matches the same thing the second group matched (space or comma)

The second big parenthesis matches or not more iterations of this sequence if started by / . 如果由/启动,则第二个大括号匹配或不匹配此序列的更多次迭代。

If all separator needs to be exactly the same, replace them by \\\\2 (just don't replace the first, that is what it is going to match for the group 2). 如果所有分隔符都必须完全相同,则用\\\\2替换它们(只是不要替换第一个,即它将与组2匹配)。

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

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