正则表达式模式1到2 [英] Regex Pattern number1 to number2
本文介绍了正则表达式模式1到2的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在搜索以下行为的模式:
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
例如
"1-2" => True
"0-0" => True
"10-22" => True
"22-10" => False
"10-10" => True
"a-b" => False
如果我可以直接提取两个int值,那也很好.
It would be also nice if I could directly extract the two int values.
推荐答案
您不能使用正则表达式比较提取的数字.您需要使用 int.TryParse
解析值,并实施其他检查以获取所需的内容.
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.
假设范围内只有 整数正数 ,则为 String.Split
和 int.TryParse 代码>方法:
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;
}
像这样称呼
int n1 = -1;
int n2 = -1;
bool result = CheckMyRange("1-2", ref n1, ref n2);
这篇关于正则表达式模式1到2的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文