Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.4k views
in Technique[技术] by (71.8m points)

c# - Regex Pattern number1 to number2

I'm searching for a pattern for the following behavior:

number1-number2
number1: Can be everything >= 0 and <= int.MaxValue
number2: Can be everything >= number1 and <= int.MaxValue

e.g.

"1-2" => True
"0-0" => True
"10-22" => True
"22-10" => False
"10-10" => True
"a-b" => False

It would be also nice if I could directly extract the two int values.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You cannot use a regex for comparing extracted numbers. You need to parse the values with int.TryParse and implement other checks to get what you need.

Assuming you only have integer positive numbers in the ranges, here is a String.Split and int.TryParse approach:

private bool CheckMyRange(string number_range, ref int n1, ref int n2)
{
    var rng = number_range.Split('-');
    if (rng.GetLength(0) != 2) 
       return false;

    if (!int.TryParse(rng[0], out n1))
       return false;
    if (!int.TryParse(rng[1], out n2))
       return false;
    if (n1 >= 0 && n1 <= int.MaxValue)
       if (n2 >= n1 && n2 <= int.MaxValue)
           return true;
    return false;
}

And call it like

int n1 = -1;
int n2 = -1;
bool result = CheckMyRange("1-2", ref n1, ref n2);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...