java如何判断字符串是否有中文

46次阅读
没有评论

共计 544 个字符,预计需要花费 2 分钟才能阅读完成。

可以使用正则表达式来判断一个字符串中是否含有中文字符。
具体的实现代码如下:

public static boolean containsChinese(String str) {String regex = "[\\u4e00-\\u9fa5]";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(str);
return matcher.find();}

该方法使用了 Unicode 中文字符范围的正则表达式 [\\u4e00-\\u9fa5] 来匹配中文字符。然后使用 Pattern 类的 compile 方法来编译正则表达式,使用 Matcher 类的 find 方法来查找字符串中是否有匹配的中文字符。
使用示例:

String str1 = "Hello 你好!";
String str2 = "Hello, World!";
System.out.println(containsChinese(str1)); // 输出:true
System.out.println(containsChinese(str2)); // 输出:false

输出结果为 true 表示字符串含有中文字符,输出结果为 false 表示字符串不含有中文字符。

丸趣 TV 网 – 提供最优质的资源集合!

正文完
 
丸趣
版权声明:本站原创文章,由 丸趣 2023-12-21发表,共计544字。
转载说明:除特殊说明外本站除技术相关以外文章皆由网络搜集发布,转载请注明出处。
评论(没有评论)