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. 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 x y z part, but I don't know how to include the '/' nor the ','
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, i.e. [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).
精彩评论