Regex for numbers only

后端 未结 18 2261
野性不改
野性不改 2020-11-22 03:29

I haven\'t used regular expressions at all, so I\'m having difficulty troubleshooting. I want the regex to match only when the contained string is all numbers; but with the

18条回答
  •  孤街浪徒
    2020-11-22 04:19

    Use the beginning and end anchors.

    Regex regex = new Regex(@"^\d$");
    

    Use "^\d+$" if you need to match more than one digit.


    Note that "\d" will match [0-9] and other digit characters like the Eastern Arabic numerals ٠١٢٣٤٥٦٧٨٩. Use "^[0-9]+$" to restrict matches to just the Arabic numerals 0 - 9.


    If you need to include any numeric representations other than just digits (like decimal values for starters), then see @tchrist's comprehensive guide to parsing numbers with regular expressions.

提交回复
热议问题