import java.util.regex.Matcher;
import java.util.regex.Pattern;
/*
正则的获取功能需要使用的类
A:Pattern(模式类)和 Matcher(匹配器) 的概述
Pattern p = Pattern.compile("a*b");
Matcher m = p.matcher("aaaaab");
boolean b = m.matches();
1. Pattern.compile(regex);
2. matcher();
3. matches();
B:案例演示
需求:获取下面这个字符串中由三个字符组成的单词
da jia ting wo shuo,hou tian bu shang ke,gao xing bu?
find()在你的字符串中,有没有符合规则的串儿
*/
public class RegexDemo9 {
public static void main(String[] args) {
//fun1();
fun2();
}
private static void fun2() {
String regex = "\\b\\w{3}\\b"; // aaa
String text = "bbb da jia ting wo shuo,hou aaa tian bu shang ke,gao xing bu?";
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(text);
//System.out.println(m.matches());
while (m.find()) {
String group = m.group();
System.out.println(group);
}
}
private static void fun1() {
Pattern p = Pattern.compile("a*b");
Matcher matcher = p.matcher("aaaaab");
boolean b = matcher.matches();
// System.out.println(b);
boolean find = matcher.find();
System.out.println(find);
}
}
|
|