Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I ensure that a string contains no more than 3 digits?

Tags:

.net

regex

I'm looking for a regex that will validate my string. The string should

  1. be 6 to 25 characters in length (any characters are allowed)
  2. not contain more than 3 digits

How can this be done?

like image 989
Adnan Zameer Avatar asked Dec 10 '25 03:12

Adnan Zameer


2 Answers

You can use negative lookahead assertion as:

^(?!.*[0-9].*[0-9].*[0-9].*[0-9]).{6,25}$

See it

which ensures that there are no 4 digits in your input.

like image 60
codaddict Avatar answered Dec 11 '25 21:12

codaddict


This can be achieved with a lookahead assertion:

^(?=(?:\D*\d){0,3}\D*$).{6,25}$

Explanation:

^           # Start of string
(?=         # Assert that the following can be matched here:
 (?:\D*\d)  # Any number of non-digits, followed by one digit
 {0,3}      # (zero to three times)
 \D*        # followed by only non-digits
 $          # until the end of the string
)           # (End of lookahead)
.{6,25}     # Match 6 to 25 characters (any characters except newlines)
$           # End of string
like image 31
Tim Pietzcker Avatar answered Dec 11 '25 21:12

Tim Pietzcker



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!