cgwebprojects
cgwebprojects

Reputation: 3472

Regex to change to must include at least a number and letter?

My regex at the minute is like this

'/[a-z0-9]{40}/i'

Which will match any string with no spaces that contains letters and/or numbers.

How can I change it so that it must at least include at least one number and at least one alphabet character so that if the string was all numbers or all letters it would not be matched?

Thanks

Upvotes: 1

Views: 738

Answers (1)

ghoti
ghoti

Reputation: 46826

/([:alpha:].*[:digit:]|[:digit:].*[:alpha:])/

This requires a number to follow a letter, or a letter to follow a number.

From your original regex, it appears that you want to enforce a requirement for 40 characters total. For that, try:

/^(.*[:alpha:].*[:digit:].*|.*[:digit:].*[:alpha:].*){40}$/

Note the extra .*'s. As long as there's one alpha and one digit, the other characters can be anything. As long as there are 40 of them.

If you want to avoid matching whitespace, replace each .* with [^[:space:]]*.

Upvotes: 2

Related Questions