java 正则 reset,正则表达式 Matcher类find() reset(),该如何解决

正则表达式 Matcher类find() reset()

本帖最后由 ljblxx 于 2013-09-22 22:24:59 编辑

public class test{

public static void main(String[] args){

Pattern p = Pattern.compile("\\d{3,5}");

String s = "123-34345-234-00";

Matcher m = p.matcher(s);

System.out.println(m.matches());

System.out.println(m.find());

System.out.println(m.find());

System.out.println(m.find());

System.out.println(m.find());

}

}

结果输出:

false

true

true

false

false

本人认为的结果:

false

true

true

false

true

另外 一个问题 就是m.reset()的作用是? 看API 那里不是很懂。

分享到:

------解决方案--------------------

matches(),find()都会影响标记,而reset()可以重置这些标记!

另外,这些标记不会循环,所以第四次已经消耗完所有字符,不可能再有true了

------解决方案--------------------

A matcher is created from a pattern by invoking the pattern's matcher method

每一次matcher方法运行的时候,便会产生一个matcher

The explicit state of a matcher includes the start and end indices of the most recent successful match.

matcher的状态包括关于最近匹配的start和end

稍微改下程序你就懂了,reset把matcher的状态清空了

import java.util.regex.Matcher;

import java.util.regex.Pattern;

public class test2{

public static void main(String[] args){

Pattern p = Pattern.compile("\\d{3,5}");

String s = "123-34345-234-00";

Matcher m = p.matcher(s);

System.out.println(m.matches());

System.out.println(m.find()+"start at:"+m.start()+" end at:"+m.end());

System.out.println(m.find()+"start at:"+m.start()+" end at:"+m.end());

//        System.out.println(m.find()+"start at:"+m.start()+" end at:"+m.end());

//        System.out.println(m.find()+"start at:"+m.start()+" end at:"+m.end());

m.reset();

System.out.println(m.find()+"start at:"+m.start()+" end at:"+m.end());

System.out.println(m.find()+"start at:"+m.start()+" end at:"+m.end());

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值