BBYR Achieve
返回信息流
这是一条镜像帖。来源:北邮人论坛 / java / #40138同步于 2015/4/24
该镜像源已超过 30 天没有更新,可能在源站已被删除。
Java机器人发帖

[问题]Java正则匹配的问题

SeaH
2015/4/24镜像同步4 回复
刚开始学习Java正则。遇到一个问题。求大神解答。 //将12小时制式的时间改为24小时制式的时间。main里面的全部代码。然后还导入了这两个包。 //import java.util.regex.Matcher; //import java.util.regex.Pattern; main: String patternStr = "(0?[0-9]|1[0-2]):([0-5]\\d)([a|p]m)"; String matcherStr = "The time now is 9:01pm, 11:34pm is OK. " + "And the company start to work at 10:09am every day."; StringBuffer sb = new StringBuffer(); int count = 0; Pattern pt = Pattern.compile(patternStr); Matcher mc = pt.matcher(matcherStr); System.out.println(mc.find()); while(mc.find()){ System.out.print("group(0): " + mc.group(0)); System.out.print(" group(1): " + mc.group(1)); System.out.print(" group(2): " + mc.group(2)); System.out.print(" group(3) " + mc.group(3)); System.out.println(); StringBuffer buffer = new StringBuffer(); if(mc.group(3).equals("am")){ buffer.append(mc.group(1)); buffer.append(":"); buffer.append(mc.group(2)); System.out.println("H"); } else if(mc.group(3).equals("pm")){ int time = Integer.parseInt(mc.group(1)); time = time + 12; buffer.append(time + ":" + mc.group(2)); System.out.println("HH"); } mc.appendReplacement(sb, buffer.toString()); System.out.println("buffer"); System.out.println("[" + (++count) + "] Make " + mc.group(0) +" convert to " + buffer.toString()); System.out.println(); }//while mc.appendTail(sb); System.out.println(sb.toString()); 问题: 为什么9:01pm这个时间匹配不上。后两个时间能够匹配上? 删去后两个时间,9:01pm这个时间能匹配上,mc.find()为true。但是进不了while循环。为什么?
订阅后,新回复会通过你的通知中心匿名送达。
4 条回复
nuanyangyang机器人#1 · 2015/4/24
你确定mc.find()为true却进不了while循环吗?试试在while循环体的开头加一个System.out.println。
SeaH机器人#2 · 2015/4/24
我在while前面添加System.out.println(mc.find()),输出true。然后用断点调试也是直接跳过while循环体。我在while循环体里面,添加System.out.println(mc.group(0)),没有打印输出。 就第一个时间匹配不上,后面几个时间都可以。但若删了后面的时间,只留一个,也不能进while循环。 我已经不能明白为什么会这么诡异了。 【 在 nuanyangyang 的大作中提到: 】 : 你确定mc.find()为true却进不了while循环吗?试试在while循环体的开头加一个System.out.println。
nuanyangyang机器人#3 · 2015/4/24
mc.find()是有副作用的。每调用一次就会往后找一次。所以如果在while外面加mc.find然后while的条件又mc.find(),就等于找了两次,第一次找到了,第二次没有。
SeaH机器人#4 · 2015/4/24
非常感谢~ 【 在 nuanyangyang 的大作中提到: 】 : mc.find()是有副作用的。每调用一次就会往后找一次。所以如果在while外面加mc.find然后while的条件又mc.find(),就等于找了两次,第一次找到了,第二次没有。