kundan bora kundan bora - 22 days ago 8
Java Question

Compare one String with multiple values in one expression

I have one String variable,

str
with possible values,
val1
,
val2
and
val3
.

I want to compare (with equal case)
str
to all of these values using an if statement, for example:

if("val1".equalsIgnoreCase(str)||"val2".equalsIgnoreCase(str)||"val3.equalsIgnoreCase(str))
{
//remaining code
}


Is there a way to avoid using multiple OR (||) operators and compare values in one expression? For example, like this:

if(("val1" OR "val2" OR "val3").equalsIgnoreCase(str) //this is only an idea.

Answer

I have found better solution this can be achieve using reg-ex -

   str.matches("val1|val2|val3");

For case insensitive matching:

   str.matches("(?i)val1|val2|val3");
Comments