Java
至于你的半宽
public static boolean isAllFullWidth(String str) {
for (char c : str.toCharArray())
if ((c & 0xff00) != 0xff00)
return false;
return true;
}
public static boolean areAnyFullWidth(String str) {
for (char c : str.toCharArray())
if ((c & 0xff00) == 0xff00)
return true;
return false;
}
和可能的
'.'
。首先将它们去掉并进行替换:'_'
正则表达式
String str="abc@gmail.com";
if (isAllFullWidth(str.replaceAll("[._]","")))
//then apart from . and _, they are all full width
所以该方法看起来像:
[\uFF01-\uFF5E]
您可以向其中添加其他角色,因此无需删除它们:
public static boolean isAllFullWidth(String str) {
return str.matches("[\\uff01-\\uff5E]*");
}
public static boolean isValidFullWidthEmail(String str) {
return str.matches("[\\uff01-\\uff5E._]*");
}
由于字母表 (a-z) 的 unicode 是
UNICODE
,因此您可以轻松区分两者97-122
用于输入
String str="abc@gmail.com";
System.out.println((int)str.charAt(0));
输出
abc@gmail.com
65345
str 将包含全角字符:
布尔标志 = str.matches("\W");
全角:> 1 字节(2,3,4.. 字节)
->比较:字符串长度==字节长度
public static final String FULL_WIDTH_CHARS = "AaBbCcDdEeFfGgHhIiJj"
+ "KkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz";
public static boolean containsFullWidthChars(String str) {
for(int i = 0; i < FULL_WIDTH_CHARS.length(); i++) {
if(str.contains(String.valueOf(FULL_WIDTH_CHARS.charAt(i)))) {
return true;
}
}
return false;
}
有了这些知识,我们现在可以使用这两种方法轻松地来回转换它们。
这会将相关的 ascii 字符转换为宽 Unicode 版本。
String strCheck = "abc@gmail.com";
if (str.length() != str.getBytes().length) {
// is Full Width
} else {
// is Half Width
}
这会将宽 Unicode 字符转换回常规 ascii。
public static char toWideCharacter(char c) {
// Check if they are the characters that are convertible.
if (c > 0x20 && c < 0x7F)
// Remove the offset and make sure we set these bytes FF00
return (char) (c - 0x20 | 0xFF00);
else return c;
}
额外学分:
这是一个生成字符串并来回转换它们以检查我们脆弱的理智的示例。
public static char fromWideCharacter(char c) {
// We can use this statement alone to check if they are wide characters.
if (c > 0xFF00 && c < 0xFF5F)
// Add the offset and mask the bits we want to keep.
return (char) (c + 0x20 & 0xFF);
else return c;
}