user5964919
user5964919

Reputation:

How to check whether a character is in a set of characters, or out of that set, in Java?

I want to compare a character whether it is in the given set characters, or out of that set, in java. --> is char 'c' in any of the sets [A-Z]or[a-z]or[0-9]

Or

--> is char 'c' out of the sets [A-Z]or[a-z]or[0-9]

Upvotes: 3

Views: 103

Answers (2)

Olivier Grégoire
Olivier Grégoire

Reputation: 35467

If you use Guava, you can use its CharMatcher class:

CharMatcher azLowerMatcher = CharMatcher.inRange('a','z');
CharMatcher azUpperMatcher = CharMatcher.inRange('A','Z');
CharMatcher zeroOneMatcher = CharMatcher.anyOf("01");
CharMatcher set = azLowerMatcher.or(azUpperMatcher).or(zeroOneMatcher);

boolean isInSet = set.matches('c');

This tool is specifically built for your use case.

Upvotes: 1

Peter Lawrey
Peter Lawrey

Reputation: 533710

You can use a regex with

boolean isAMatch = Character.toString(ch).matches("[A-Za-z01]")

Upvotes: 2

Related Questions