一、使用matches()
- Pattern p = Pattern.compile("正则表达式");
- Matcher m = p.matcher("预匹配的字符串");
- if(m.matches()) {
- m.group(1); //匹配第1项
- m.group(2); //匹配第2项
- }
二、使用find()
public static void main(String[] args) {
int count = 0;
String regEx = "[\\u4e00-\\u9fa5]";
String str = "中文fdas ";
Pattern p = Pattern.compile(regEx);
Matcher m = p.matcher(str);
while (m.find()) {
count = count + 1;
System.out.println(m.groupCount());
System.out.println(m.group());
}
System.out.println("共有 " + count + "个 ");
}
结果:
0
中
0
文
共2个
本文介绍了如何在Java中使用正则表达式进行文本匹配,包括使用matches()和find()方法。通过实例展示了如何查找特定字符并计算其出现次数。
1664

被折叠的 条评论
为什么被折叠?



