您好,
我正在开发GWT应用程序,用户可以用日语输入其个人信息。但是“用户ID”和“密码”应仅包含英文字符(拉丁字母)。如何对字符串进行验证?
您好,
我正在开发GWT应用程序,用户可以用日语输入其个人信息。但是“用户ID”和“密码”应仅包含英文字符(拉丁字母)。如何对字符串进行验证?
String#matches()
方法,结合适当的 regex,来完成此操作。拉丁字符可以使用 \w
匹配。boolean valid = input.matches("\\w+");
_
。不确定是否有害。否则,您可以使用[A-Za-z]+
。String clean = Normalizer.normalize(input, Form.NFD).replaceAll("\\p{InCombiningDiacriticalMarks}+", "");
boolean valid = clean.matches("\\w+");
更新: Java 中有一个未记录的正则表达式,可以匹配变音符号,即 \p{L}
。
boolean valid = input.matches("\\p{L}+");
以上适用于Java 1.6。
\p{L}
已有官方文档:http://java.sun.com/javase/6/docs/api/java/util/regex/Pattern.html#ubc - Joachim Sauer\p{L}
也包括很多非拉丁字母。 - Thilo\p{script=Latin}
。 - Thilopublic static boolean isValidISOLatin1 (String s) {
return StandardCharsets.US_ASCII.newEncoder().canEncode(s);
} // or "ISO-8859-1" for ISO Latin 1
StandardCharsets.US_ASCII
。 - Grigory Kislinpublic static boolean isStringContainsLatinCharactersOnly(final String iStringToCheck)
{
return iStringToCheck.matches("^[a-zA-Z0-9.]+$");
}
可能有更好的方法,但您可以加载一个包含您认为可接受的字符的集合,然后将用户名/密码字段中的每个字符与该集合进行比较。
伪代码:
foreach (character in username)
{
if !allowedCharacters.contains(character)
{
throw exception
}
}
对于这样简单的事情,我会使用正则表达式。
private static final Pattern p = Pattern.compile("\\p{Alpha}+");
static boolean isValid(String input) {
Matcher m = p.matcher(input);
return m.matches();
}
还有其他预定义的类别,例如\w
,可能更适合。
我成功地使用了用户232624、Joachim Sauer和Tvaroh的答案的组合:
static CharsetEncoder asciiEncoder = Charset.forName("US-ASCII"); // or "ISO-8859-1" for ISO Latin 1
boolean isValid(String input) {
return Character.isLetter(ch) && asciiEncoder.canEncode(username);
}