您将如何检查 Java 中的字符是否可键入?

How would you check if a char in Java is typeable?

标题几乎说明了一切,我如何检查一个字符是否可以在 java 中输入? 我所说的可键入的意思不仅是它是一个字母或数字,而且还包括它是一个感叹号或空格等

我不希望诸如转义和退格字符之类的东西通过过滤器。

我知道 Character.isLetter() 但这不是我想要的,结果太窄了。

当然我可以使用黑名单/白名单过滤器,但是因为这很不方便,所以我更喜欢一个更实用的解决方案。

我认为最好的方法是使用正则表达式。您可以准确指定哪些字符是 "typeable".

从字符串的角度来看,例如将 char 视为单个字符串,您可以使用正则表达式(带有字符 class)来定义您认为有效的字符。

例如,你可以有这样的东西:

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

因此,您可以在正则表达式字符 class 中定义有效字符。更详细的例子可以是:

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");

您可以通过将所有字符放在 [] 中来定义 regex character class 中的有效字符。因此,对于上面的示例,正​​则表达式图如下所示:

您可以使用其中一种 Character.isISOControl 方法,如果它是一个控制字符,那么就我认为您的意思而言,它不可 可输入。

来自wikipedia

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

这是一个奇怪的问题,因为您不知道 char 来自哪个键盘。

如果您想检查 char 的性质,您可以使用正则表达式:

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

Pattern

中了解有关正则表达式的更多信息

现在,如果您想检查 按键事件,您需要告诉我们您正在使用哪个 API 或框架,或者您使用的是哪种应用程序尝试构建,因为它会改变您检查这些事件的方式。