java - java中如何检查字符串是否具有全角字符

标签 java string character special-characters

有人可以建议我如何检查 String 中是否包含 Java 中的全角字符吗?全角字符是特殊字符。

字符串中的全角字符:

abc@gmail.com

字符串中的半角字符:

abc@gmail.com

最佳答案

我不确定您是在寻找其中一个还是全部,因此以下是两者的函数:

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._]*");
}

关于java - java中如何检查字符串是否具有全角字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29508932/

相关文章:

java - 从 Java Servlet 向 Web API 发送 get 请求

c - 在C中输出字符串中的变量内容

php - 如何限制从数据库回显的字符?

C - SizeOf 指针

c - GDB 调试器 : char array type examine and print command

java - JFrame 重绘/重载

java - 使用 IIR 滤波器生成粉红噪声

java - 不关闭游标或数据库对象?

python - 如何通过 Python 字符串切片大步反转字符串

java - 将对象类型声明为 String