java 重置程序_Java Pattern Matcher:创建新的或重置?

假定一个正则表达式,它通过Java Matcher对象匹配大量的字符串:

String expression = ...; // The Regular Expression

Pattern pattern = Pattern.compile(expression);

String[] ALL_INPUT = ...; // The large number of strings to be matched

Matcher matcher; // Declare but not initialize a Matcher

for (String input:ALL_INPUT)

{

matcher = pattern.matcher(input); // Create a new Matcher

if (matcher.matches()) // Or whatever other matcher check

{

// Whatever processing

}

}

在Java SE 6 JavaDoc for Matcher中,可以通过reset(CharSequence)方法重新使用相同Matcher对象的选项,如同源代码所示,它比每次都创建一个新的Matcher有点便宜,即与上面不同的是可以做:

String expression = ...; // The Regular Expression

Pattern pattern = Pattern.compile(expression);

String[] ALL_INPUT = ...; // The large number of strings to be matched

Matcher matcher = pattern.matcher(""); // Declare and initialize a matcher

for (String input:ALL_INPUT)

{

matcher.reset(input); // Reuse the same matcher

if (matcher.matches()) // Or whatever other matcher check

{

// Whatever processing

}

}

应该使用上面的reset(CharSequence)模式,还是应该更喜欢每次初始化一个新的Matcher对象?

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值