I want to use only regular expression
Raida => true
raida => false
raiDa => true
I have tried this :
String string = "Raida"
boolean bool = string.contains("?=.*[A-Z]");
System.out.println(bool);
but it is not working
I want to use only regular expression
Raida => true
raida => false
raiDa => true
I have tried this :
String string = "Raida"
boolean bool = string.contains("?=.*[A-Z]");
System.out.println(bool);
but it is not working
A simple solution would be:
boolean hasUpperCase = !string.equals(string.toLowerCase());
You convert the String to lowercase, if it is equal to the original string then it does not contain any uppercase letter.
In your example Raida
you'll be compairing
Raida
to raida
these two are not equal so meaning the original string contains an uppercase letter
The answer with regular expression solution has already been posted as well as many other rather convenient options. What I would also suggest here is using Java 8 API for that purpose. It might not be the best option in terms of performance, but it simplifies code a lot. The solution can be written within one line:
string.chars().anyMatch(Character::isUpperCase);
The benefit of this solution is readability. The intention is clear. Even if you want to inverse it.
Something which is close to your original idea. You basically just check whether there is a part in the string which contains an upper case letter - there can be any other characters after and before it. Here I included a small main method for testing purposes.
public static void main(String[] args) {
test("raid");
test("raId");
test("Raida");
test("R");
test("r");
test(".");
test("");
}
public static void test(String word) {
//(?s) enables the DOTALL mode
System.out.println(word + " -> " + word.matches("(?s).*[A-Z].*"));
}
I edited the example to deal with line breaks too. I just tested in on a Windows machine. This now uses DOTALL: https://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html#DOTALL. In this mode, the expression . matches any character, including a line terminator.
You can replace all non UpperLetter and calculate the length, if it is great or equal to 1 this mean there are at least one upper letter :
String input = "raiDa";
boolean check = input.replaceAll("[^A-Z]", "").length() >= 1;
Beside String::contain
not use regex read the documentation
Your pattern just needs to be surrounded by ()
.
Pattern pattern = Pattern.compile("(?=.*[A-Z])");
Matcher matcher = pattern.matcher(string);
while (matcher.find()) {
bool = true;
}
If you want an alternative to regex
, try using Character.isUpperCase()
.
boolean bool = false;
for (int i = 0; i < string.length(); i++) {
char c = string.charAt(i);
if (Character.isUpperCase(c)) {
bool = true;
break;
}
}
System.out.println(bool);