考虑下面的代码:避免代码重复
if (matcher1.find()) {
String str = line.substring(matcher1.start()+7,matcher1.end()-1);
/*+7 and -1 indicate the prefix and suffix of the matcher... */
method1(str);
}
if (matcher2.find()) {
String str = line.substring(matcher2.start()+8,matcher2.end()-1);
method2(str);
}
...
我有n个的匹配,匹配器全部是独立的(如果是真的,它没有提到其他人......),用于这是真正的每个匹配 - 我对其匹配的内容调用了不同的方法。
问题:我不喜欢这里的代码重复或“魔术数字”,但我想知道是否有更好的方法来做到这一点......? (也许游客模式?)有什么建议吗?
如果它们是独立的,则应该能够制作大正则表达式并使用http://download.oracle.com/javase/tutorial/essential/regex/groups.html遍历子字符串。 – helpermethod 2011-04-07 08:23:24
@Helper:404在你的链接上,“to”连接到.html – amit 2011-04-07 08:27:52
http://download.oracle.com/javase/tutorial/essential/regex/groups.html – helpermethod 2011-04-07 08:53:39