我正在搜索以下行为的模式:
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值提取出来就好了。
最佳答案
您不能使用正则表达式来比较提取的数字。您需要使用 int.TryParse
解析这些值并实现其他检查以获得您需要的内容。
假设范围内只有整数正数,这里是一个String.Split
和int.TryParse
方法:
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);
关于c# - 正则表达式模式 number1 到 number2,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32606905/