Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

check if string contains both number and letter (at least)

Tags:

regex

I wish to check if a password contains at least one letter and a number. special characters are accepted but not required...

That will be a simple password checker.

like image 764
FallenAngel Avatar asked Dec 13 '10 14:12

FallenAngel


People also ask

How do you check if a string contains both numbers and letters?

To check whether a String contains only unicode letters or digits in Java, we use the isLetterOrDigit() method and charAt() method with decision-making statements. The isLetterOrDigit(char ch) method determines whether the specific character (Unicode ch) is either a letter or a digit.

How do you check if a string contains both letters and numbers in JavaScript?

In order to verify that the string only contains letters, numbers, underscores and dashes, we can use the following regex: "^[A-Za-z0-9_-]*$".

How do you check if a string has at least one letter and one number in Python?

Letters can be checked in Python String using the isalpha() method and numbers can be checked using the isdigit() method.

Which of these contains both letter and number?

It's called the coefficient. For example: 5x, the number 5 is the coefficient. For the letter x, Then the number 1 is understood to be the coefficient.


2 Answers

You can use lookahead assertions to check for existence of any digit and any letter as:

^(?=.*[a-zA-Z])(?=.*[0-9])
like image 87
codaddict Avatar answered Oct 16 '22 16:10

codaddict


Using a single regex for this can lead to somewhat unreadable/unreliable code. It may make more sense to use simpler regexes eg [0-9] to check for the existence of a digit and break the requirements of your password strength checker into a multi-line if. Also this allows you to know more readily at what stage the validation failed and possibly make suggestions to the user.

like image 33
El Ronnoco Avatar answered Oct 16 '22 16:10

El Ronnoco