Matcher matches() 标识字符串是否和正则表达式匹配
public static void main(String[] args) {
Pattern p = Pattern.compile("^[0-9]+$");
String str = "123";
Matcher m = p.matcher(str);
System.out.println(m.matches());
}
输出
Matcher find() 找到下一个匹配的子串,有个列子:你好<p>hello</p><p>regular</p>,我们需要匹配<p></p> 标签和标签包含内容,这里包含了2个匹配的子串<p>hello</p> 和 <p>regular</p>
public static void main(String[] args) {
Pattern p = Pattern.compile("(<p>.*?</p>)");
String str = "你好<p>hello</p><p>regular</p>";
Matcher m = p.matcher(str);
while (m.find()) {
System.out.println(m.group());
}
}
输出
正则.*后面加?是为了启用非贪婪模式,尽可能小的匹配到第一个</p>就结束,把问号去掉的话会直接匹配最左边<p>和最右边</p>。
关于Matcher group(int group)用法,就是获取已匹配字符串的第几个分组内容,group()是获取整个匹配的字符串。正则表达式()括号代表分组
public static void main(String[] args) {
Pattern p = Pattern.compile("([a-z])([0-9])");
Matcher matcher = p.matcher("a1b2");
while (matcher.find()) {
System.out.println(matcher.group());
System.out.println(matcher.group(1));
System.out.println(matcher.group(2));
System.out.println("==============================");
}
}
输出