Identify if a string is a number

前端 未结 25 3059
無奈伤痛
無奈伤痛 2020-11-22 00:13

If I have these strings:

  1. \"abc\" = false

  2. \"123\" = true

  3. \"ab2\"

25条回答
  •  醉酒成梦
    2020-11-22 00:21

    This will return true if input is all numbers. Don't know if it's any better than TryParse, but it will work.

    Regex.IsMatch(input, @"^\d+$")
    

    If you just want to know if it has one or more numbers mixed in with characters, leave off the ^ + and $.

    Regex.IsMatch(input, @"\d")
    

    Edit: Actually I think it is better than TryParse because a very long string could potentially overflow TryParse.

提交回复
热议问题