Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I test if a string contains any uppercase letter using Java with regular expression? [duplicate]

Tags:

java

regex

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

like image 594
Shadiqur Avatar asked Nov 30 '17 07:11

Shadiqur


2 Answers

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

like image 174
Ayo K Avatar answered Sep 17 '22 13:09

Ayo K


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.

like image 35
dvelopp Avatar answered Sep 16 '22 13:09

dvelopp