可以的,Java 的正则表达式(regex)完全可以匹配中文,前提是你理解字符编码和正则写法。
Java 内部使用 Unicode,中文字符在 Unicode 中位于:
\u4E00 – \u9FA5\u3400 – \u4DB5所以可以用 Unicode 范围来匹配中文。
String regex = "[\\u4E00-\\u9FA5]";
示例:
"中".matches("[\\u4E00-\\u9FA5]"); // true
String regex = "[\\u4E00-\\u9FA5]+";
示例:
"中文测试".matches("[\\u4E00-\\u9FA5]+"); // true
"中文abc".matches("[\\u4E00-\\u9FA5]+"); // false
String regex = ".*[\\u4E00-\\u9FA5].*";
\p{IsHan}(推荐,更规范)Java 支持 Unicode 属性:
String regex = "\\p{IsHan}";
匹配任意汉字(比 \u4E00-\u9FA5 更全面)。
"汉字".matches("\\p{IsHan}+"); // true
import java.util.regex.*;
public class Test {
public static void main(String[] args) {
String text = "abc中文123测试";
Pattern p = Pattern.compile("\\p{IsHan}+");
Matcher m = p.matcher(text);
while (m.find()) {
System.out.println(m.group());
}
}
}
输出:
中文
测试
String.matches() 是全匹配,不是包含匹配\p{IsHan} 而不是固定区间如果你有具体场景(比如:校验、提取、替换、Spring 校验注解等),可以告诉我,我可以给你更合适的正则。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。