Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to check all character in a string is lowercase using java

Tags:

java

regex

I tried like this but it outputs false,Please help me

String inputString1 = "dfgh";// but not dFgH
String regex = "[a-z]";
boolean result;

Pattern pattern1 = Pattern.compile(regex);
Matcher matcher1 = pattern1.matcher(inputString1);
result = matcher1.matches();
System.out.println(result);
like image 511
sunleo Avatar asked Nov 13 '12 17:11

sunleo


1 Answers

Your solution is nearly correct. The regex must say "[a-z]+"—include a quantifier, which means that you are not matching a single character, but one or more lowercase characters. Note that the uber-correct solution, which matches any lowercase char in Unicode, and not only those from the English alphabet, is this:

"\\p{javaLowerCase}+"

Additionally note that you can achieve this with much less code:

System.out.println(input.matches("\\p{javaLowerCase}*"));

(here I am alternatively using the * quantifier, which means zero or more. Choose according to the desired semantics.)

like image 169
Marko Topolnik Avatar answered Oct 20 '22 22:10

Marko Topolnik