Regex Pattern number1 to number2

前端 未结 3 1352
耶瑟儿~
耶瑟儿~ 2021-01-21 22:37

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

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


        
3条回答
  •  再見小時候
    2021-01-21 23:32

    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);
    

提交回复
热议问题