在 Java 中,正则匹配中文主要依赖于 Unicode 范围 或 Unicode 属性。下面按常见场景说明。
String regex = "[\\u4e00-\\u9fa5]";
示例:
String text = "你好Hello世界";
String regex = "[\\u4e00-\\u9fa5]+";
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(text);
while (m.find()) {
System.out.println(m.group());
}
输出:
你好
世界
✅ 覆盖:基本汉字(最常用)
String regex = "[\\u4e00-\\u9fff]";
或更完整:
String regex = "[\\u3400-\\u4dbf\\u4e00-\\u9fff\\uf900-\\ufaff]";
String regex = "\\p{IsIdeographic}";
或:
String regex = "\\p{script=Han}";
示例:
String regex = "\\p{script=Han}+";
✅ 优点:
boolean hasChinese = text.matches(".*[\\u4e00-\\u9fa5].*");
正则写在字符串中时:
"\\u4e00" // 正确
"\u4e00" // 错误(会被当成真实字符)
text.matches("[\\u4e00-\\u9fa5]+");
"[\\u4e00-\\u9fa5\\d]+"
"[\\u4e00-\\u9fa5]{2,5}"
如果你有具体场景(比如:校验姓名、提取中文、过滤 emoji、中文标点等),可以告诉我,我给你更精确的正则。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。