Regex looking for a specific number of digits per line?

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

I would like to test this with RegularExpressionValidator, but I'm not quite sure how to write a regex.

I guess this will look like a regular expression for a phone number, but the phone number at least has some common formats.

+4
source share
3 answers

Below will correspond an input string containing at least n digits:

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

where n is an integer value.

Brief explanation:

  • \D* matches zero or more characters without digits ( \D is a short hand for [^0-9] or [^\d] );
  • therefore, \D*\d matches zero or more characters without digits, followed by a digit;
  • and (\D*\d){n} and repeats the previous n times.
+12
source

I would approach it like this:

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

In words, it will look for 10 digits, each of which is surrounded by 0 or more characters. Because the. * Are greedy, any additional numbers will also be matched by him.

In any case, check out http://regexlib.com/RETester.aspx . It is hard to write a regex without checking.

+3
source

in order to have at least n digits, you need to use the following regular expression:

(\ D * \ r) {n,}

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

Regards, Carlo.

0
source

Source: https://habr.com/ru/post/1315536/


All Articles