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.