How can you check if a char in Java is valid?

The title pretty much says it all, how could I check if a char is in java? And what I mean by type is not only if it is a letter or number, but also if it is an exclamation point or space, etc.

I don't want objects like escape and backslash characters to go through the filter.

I know Character.isLetter()

, but that's not what I want, the result is too narrow.

Of course, I could use a blacklist / whitelist filter, but since this is rather inconvenient, I would prefer a slightly more practical solution if it is one.

+3


source to share


4 answers


You can use one of the methods Character.isISOControl

, if it is a control character then it cannot be printed in the way I think you mean.

From wikipedia :



In computing and telecommunications, a control character or non-printable character is a code point (number) in a character set that does not represent a written character.

+2


source


I think the best way to do this is using regular expressions. You can specify exactly which characters are "printed".



0


source


From a String perspective, considering, for example, char as a single character string, you can use a regular expression (with a character class) to determine what you think is valid.

For example, you can have something like this:

assertTrue("a".matches("[\\w!?/-]")); // Bear in mind that \w is [a-zA-Z0-9]
assertTrue("!".matches("[\\w!?/-]"));
assertTrue("?".matches("[\\w!?/-]"));
assertFalse(":".matches("[\\w!?/-]"));

      

So, you can define valid characters in the regex character class. A more detailed example could be:

String charToTest = "W";
String validCharsRegex = "^[A-Za-z0-9!@#$%^&*)(-]$"; // Put withing [...] what
                                                     //  you consider valid characters

if (charToTest.matches(validCharsRegex))
    System.out.println("Valid character");
else
    System.out.println("Invalid character");

      

You can define your valid characters in the regex character class by putting all characters in and . So for the above example, the regex diagram looks like this: [

]

Regular expression visualization

0


source


This is a weird question, because you don't know which keyboard the char appears from since its appearance.

If you want to check the character of a char , you can use regular expressions:

char a = 'a';
String.valueOf(a).matches(".*"); // returns true

      

Learn more about regular expressions in Pattern

Now, if you want to check that the keys were pressed keys , you need to tell us which API or framework you are using, or which application you are trying to build, as it will be different from how you can check these events.

0


source







All Articles