简体   繁体   中英

How to check whether the given string is boolean or not in Java?

I have one string. I have to verify whether it is of type boolean or not?

The conditions for Boolean are below:

{ TRUE,True,true,T,t,YES,Yes,yes,Y,y}

and the same for negative case also.

You can use String.matches(String)

if (map.get(key).matches("(?i)t(rue)?|y(es)?")) {
  // true boolean
} else if (map.get(key).matches("(?i)f(alse)?|n(o)?")) {
  // false boolean
} else {
  // not boolean
}

The argument to matches is a regular expression.

(?i) says to ignore case.

the form t(rue)? says just t or true (the rue is optional)

| (bar character) is like saying or

the rest of the words are defined like true

Set up a set, once:

static final Set<String> trueStrings = new HashSet<>(Arrays.asList("TRUE", "true", "True", "T", "t", "YES", "Yes", "yes", "Y", "y"));

and then, each time you want to test a string:

boolean isTrue = trueStrings.contains(yourString);

Rather than duplicating your code with

"true".equals(map.get(key).toString()) || "TRUE".equals(map.get(key).toString()) || True".equals(map.get(key).toString())

your can use the equalsIgnoreCase method so it becomes

"true".equalsIgnoreCase(map.get(key).toString())

Likewise with t and T

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM