In C#, how to check whether a string contains an integer?

后端 未结 8 1238
慢半拍i
慢半拍i 2020-12-28 12:43

I just want to know, whether a String variable contains a parsable positive integer value. I do NOT want to parse the value right now.

Currently I

8条回答
  •  渐次进展
    2020-12-28 13:31

    You can check if string contains numbers only:

    Regex.IsMatch(myStringVariable, @"^-?\d+$")
    

    But number can be bigger than Int32.MaxValue or less than Int32.MinValue - you should keep that in mind.

    Another option - create extension method and move ugly code there:

    public static bool IsInteger(this string s)
    {
       if (String.IsNullOrEmpty(s))
           return false;
    
       int i;
       return Int32.TryParse(s, out i);
    }
    

    That will make your code more clean:

    if (myStringVariable.IsInteger())
        // ...
    

提交回复
热议问题