Java正则表达式 matches find group

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("==============================");
		}
	}

输出

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值