

package net.nyist.jhlishero;
import java.util.regex.*;
public class TestPattern {
public static void main(String[] args) {
//定义正则表达式与被匹配的字符串
String regex = "(0?[1-9]|1[0-2]):([0-5]\\d)([a|p]m)";
String matcherStr = "现在在时间是:12:25am, 这里的营业时间是:08:00am 到 5:30pm!!!!";
//生成目标字符串与Matcher对象
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(matcherStr);
//创建目标字符串缓冲区
StringBuffer sb = new StringBuffer();
//定义计数器
int count = 0;
//打印初始字符串
System.out.println("初始字符串是:" + matcherStr);
//开始匹配检查
while(m.find()) {
//创建临时字符串缓冲区
StringBuffer temp = new StringBuffer();
if(m.group(3).equals("am")) {
//时间为am的情况的替换工作
//设置时间的格式
temp.append(m.group(1));
temp.append(":");
temp.append(m.group(2));
} else {
//时间为pm的情况的替换工作
//提取时间并转换
int time = Integer.parseInt(m.group(1)) + 12;
temp.append(time);
temp.append(":");
temp.append(m.group(2));
}
//进行替换并将结果放入目标字符串缓冲区
m.appendReplacement(sb, temp.toString());
System.out.println("[" + (++count) + "] ----" + m.group(0) + "替换为" + temp.toString()) ;
}
m.appendTail(sb);
System.out.println("最后的结果是:" + sb.toString());
}
}