Reputation: 10943
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);
Upvotes: 9
Views: 29461
Reputation: 382102
Use this pattern :
String regex = "[a-z]*";
Your current pattern only works if the tested string is one char only.
Note that it does exactly what it looks like : it doesn't really test if the string is in lowercase but if it doesn't contain chars outside [a-z]
. This means it returns false for lowercase strings like "àbcd"
. A correct solution in a Unicode world would be to use the Character.isLowercase() function and loop over the string.
Upvotes: 3
Reputation: 36601
Why bother with a regular expression ?
String inputString1 = "dfgh";// but not dFgH
boolean result = inputString1.toLowerCase().equals( inputString1 );
Upvotes: 0
Reputation: 46408
you are almost there, except that you are only checking for one character.
String regex = "[a-z]+";
the above regex would check if the input string would contain any number of characters from a
to z
read about how to use Quantifiers in regex
Upvotes: 5
Reputation: 200148
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.)
Upvotes: 22
Reputation: 32787
It should be
^[a-z]+$
^
is the start of string
$
is the end of string
[a-z]+
matches 1 to many small characters
You need to use quantifies like *
which matches 0 to many chars,+
which matches 1 to many chars..They would matches 0 or 1 to many times of the preceding character or range
Upvotes: 2