Brandon
Brandon

Reputation: 69983

Regex for at least a certain number of digits in a string

When a user submits a form I need to make sure that the input contains at least a minimum number of digits. The problem is that I don't know what format the input will be in. The digits likely won't be in a row, and might be separated by letters, punctuation, spaces, etc. I don't care about the rest of the string.

I'd like to check this with a RegularExpressionValidator but I'm not quite sure how to write the regex.

I guess this would be similar to a phone number regex, but a phone number at least has some common formats.

Upvotes: 4

Views: 6892

Answers (3)

Slider345
Slider345

Reputation: 4758

I would approach it something like this:

Regex.IsMatch(input, @"^([^0-9]*[0-9]){10}.*$");

In words, this would search for 10 digits, each of which are surrounded by 0 or more characters. Since the .* are greedy, any additional digits would be matched by them as well.

Anyway, check out http://regexlib.com/RETester.aspx It can be really hard to write a regular expression without something to test against.

Upvotes: 3

Karlo Smid
Karlo Smid

Reputation: 545

in order to have at least n digits, you need to use following regex:

(\D*\d){n,}

Regex (\D*\d){n} will match exactly n digits.

Regards, Karlo.

Upvotes: 0

Bart Kiers
Bart Kiers

Reputation: 170158

The following will match an input string containing at least n digits:

Regex.IsMatch(input, @"(\D*\d){n}");

where n is an integer value.

A short explanation:

  • \D* matches zero or more non-digit chars (\D is a short hand for [^0-9] or [^\d]);
  • so \D*\d matches zero or more non-digit chars followed by a digit;
  • and (\D*\d){n} groups, and repeats, the previous n times.

Upvotes: 13

Related Questions