How to Check Whether a String Contains Lowercase Letter, Uppercase Letter, Special Character and Digit

How to check whether a string contains lowercase letter, uppercase letter, special character and digit?

This does what you want in java as a single regex, although I would personally use something like the solution provided by Mark Rhodes. This will get ridiculous quick (if it isn't already...) as the rules get more complicated.

String regex = "^(?=.*?\\p{Lu})(?=.*?[\\p{L}&&[^\\p{Lu}]])(?=.*?\\d)" + 
"(?=.*?[`~!@#$%^&*()\\-_=+\\\\\\|\\[{\\]};:'\",<.>/?]).*$"
  1. ^ This matches the beginning of the string. It's not strictly necessary for this to work, but I find it helps readability and understanding. Also, using it when you can often makes a big performance improvement and is almost never a penalty.

  2. (?=X) This is called a positive lookahead. Basically what we're saying is "The beginning of the string (^) must be followed by this thing X in order for a match, but DO NOT advance the cursor to the end of X, stay at the beginning of the line. (that's the "look ahead" part.)

  3. .*?\p{Lu} eat characters after the beginning of the line until you find a capital letter. This will fail to match if no capital letter is found. We use \p{Lu} instead of A-Z because we don't want people from other parts of the world to throw up their hands and complain about how our software was written by an ignorant American.

  4. Now we go back to the beginning of the line (we go back because we used lookahead) and start a search for .*?[\p{L}&&[^\p{Lu}]] shorthand for "all letters, minus the capitals" (hence matches lower case).

  5. .*?\d + .*?[`~!@#$%^&*()\-_=+\\\|\[{\]};:'\",<.>/?] repeat for digits and for your list of special characters.

  6. .*$ Match everything else until the end of the line. We do this just because of the semantics of the 'matches' methods in java that see if the entire string is a match for the regex. You could leave this part of and use the Matcher#find() method and get the same result.

  7. The Owl is one of the best books ever written on any technical subject. And it's short and fast to read. I cannot recommend it enough.

Check if a string contains at least a upperCase letter, a digit, or a special character in Swift?

Simply replace your RegEx rule [A-Z]+ with .*[A-Z]+.* (and other RegEx rules as well)

Rules

[A-Z]+ matches only strings with all characters capitalized

Examples: AVATAR, AVA, TAR, AAAAAA

Won't work: AVATAr

.* matches all strings (0+ characters)

Examples: 1, 2, AVATAR, AVA, TAR, a, b, c

.*[A-Z]+.* matches all strings with at least one capital letter

Examples: Avatar, avataR, aVatar

Explanation:

I. .* will try to match 0 or more of anything

II. [A-Z]+ will require at least one capital letter (because of the +)

III. .* will try to match 0 or more of anything

Avatar [empty | "A" | "vatar"]

aVatar ["a" | "V" | "atar"]

aVAtar ["a" | "VA" | "tar"]

Working Code

func checkTextSufficientComplexity(var text : String) -> Bool{


let capitalLetterRegEx = ".*[A-Z]+.*"
var texttest = NSPredicate(format:"SELF MATCHES %@", capitalLetterRegEx)
var capitalresult = texttest!.evaluateWithObject(text)
println("\(capitalresult)")


let numberRegEx = ".*[0-9]+.*"
var texttest1 = NSPredicate(format:"SELF MATCHES %@", numberRegEx)
var numberresult = texttest1!.evaluateWithObject(text)
println("\(numberresult)")


let specialCharacterRegEx = ".*[!&^%$#@()/]+.*"
var texttest2 = NSPredicate(format:"SELF MATCHES %@", specialCharacterRegEx)

var specialresult = texttest2!.evaluateWithObject(text)
println("\(specialresult)")

return capitalresult || numberresult || specialresult

}

Examples:

checkTextSufficientComplexity("Avatar") // true || false || false
checkTextSufficientComplexity("avatar") // false || false || false
checkTextSufficientComplexity("avatar1") // false || true || false
checkTextSufficientComplexity("avatar!") // false || false || true

RegEx to make sure that the string contains at least one lower case char, upper case char, digit and symbol

If you need one single regex, try:

(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*\W)

A short explanation:

(?=.*[a-z])        // use positive look ahead to see if at least one lower case letter exists
(?=.*[A-Z]) // use positive look ahead to see if at least one upper case letter exists
(?=.*\d) // use positive look ahead to see if at least one digit exists
(?=.*\W) // use positive look ahead to see if at least one non-word character exists

And I agree with SilentGhost, \W might be a bit broad. I'd replace it with a character set like this: [-+_!@#$%^&*.,?] (feel free to add more of course!)

How to check if string contains both uppercase and lowercase characters

For only minimum 1 upper and minimum 1 Lower only, you could use this RegEx:

RegExp regEx = new RegExp(r"(?=.*[a-z])(?=.*[A-Z])\w+");
String a = "aBc";
String b = "abc";
String c = "ABC";
print("a => " + regEx.hasMatch(a).toString());
print("b => " + regEx.hasMatch(b).toString());
print("c => " + regEx.hasMatch(c).toString());

Expected Result:

I/flutter (10220): a => true
I/flutter (10220): b => false
I/flutter (10220): c => false

Reusable

extension StringValidators on String {

meetsPasswordRequirements() {
RegExp regEx = new RegExp(r"(?=.*[a-z])(?=.*[A-Z])\w+");
return regEx.hasMatch(this);
}

}

Use

final isValid = text.meetsPasswordRequirements();

How can I test if a letter in a string is uppercase or lowercase using JavaScript?

The answer by josh and maleki will return true on both upper and lower case if the character or the whole string is numeric. making the result a false result.
example using josh

var character = '5';
if (character == character.toUpperCase()) {
alert ('upper case true');
}
if (character == character.toLowerCase()){
alert ('lower case true');
}

another way is to test it first if it is numeric, else test it if upper or lower case
example

var strings = 'this iS a TeSt 523 Now!';
var i=0;
var character='';
while (i <= strings.length){
character = strings.charAt(i);
if (!isNaN(character * 1)){
alert('character is numeric');
}else{
if (character == character.toUpperCase()) {
alert ('upper case true');
}
if (character == character.toLowerCase()){
alert ('lower case true');
}
}
i++;
}

Check if string contains at least one of each: lowercase letter, uppercase letter, number, and special character

Change (?=.*?^[a-zA-Z0-9_@.-]) with the below one:

       + see here
(?=.*?[^a-zA-Z0-9_@.-])
^^ i kept the dot, hyphen, etc as you used, if you don't need, remove.

In this regex, the ^ inside the character class [] is negating the characters. You were almost there, just unfortunately you have placed that outside the []

How do I check if a Java String contains at least one capital letter, lowercase letter, and number?

For a simple string check, a single sweep through the string is enough. Since Regex will not offer any significant benefit, here is a simple for loop to achieve the same :

private static boolean checkString(String str) {
char ch;
boolean capitalFlag = false;
boolean lowerCaseFlag = false;
boolean numberFlag = false;
for(int i=0;i < str.length();i++) {
ch = str.charAt(i);
if( Character.isDigit(ch)) {
numberFlag = true;
}
else if (Character.isUpperCase(ch)) {
capitalFlag = true;
} else if (Character.isLowerCase(ch)) {
lowerCaseFlag = true;
}
if(numberFlag && capitalFlag && lowerCaseFlag)
return true;
}
return false;
}

Test run:

System.out.println(checkString("aBCd1")); // output is true
System.out.println(checkString("abcd")); //output is false

I think this should help OP's particular problem.

how to check whether a stream has uppercase , lowercase and digits or not using stream in java

You could use the methods defined in Character class to filter the input character stream.

input.chars()
.filter(X -> Character.isUpperCase(X) ||
Character.isLowerCase(X) ||
Character.isDigit(X)
)
.forEach(System.out::println);

EDIT:

To get a boolean result of whether such character exists in the stream, use anyMatch() instead of filter.

    if (input.chars()
.anyMatch(X -> Character.isUpperCase(X) || Character.isLowerCase(X) || Character.isDigit(X))) {
System.out.println("Yes");
} else {
System.out.println("No");
}

EDIT 2:

Im not sure if you are checking if the stream contains ALL OF THEM or AT LEAST ONE OF THEM. The above answer is for contains at least one. If you are looking for all of the characters, just change the || to &&.

RegEx to make sure that the string contains at least one uppercase and lowercase letter but also may include numbers and special characters

You can use positive lookahead patterns to ensure that there are at least one uppercase and one lowercase characters, while using a character set to cover the rest of the allowed characters:

^(?=[a-z0-9!@#$%^&*()+=?]*[A-Z])(?=[A-Z0-9!@#$%^&*()+=?]*[a-z])[A-Za-z0-9!@#$%^&*()+=?]*$

Demo: https://regex101.com/r/Uyy1aj/2



Related Topics



Leave a reply



Submit