java处理文本文件时经常用到字符串匹配处理,那么正则表达式无疑是最佳选择
其实正则表达式的使用非常简单,关键是正则表达式的编写,正则表达式参见http://twb.iteye.com/blog/196682
下面写一下java正则表达式的处理,已备日后查阅
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Test {
public void PatternTest() {
String exp = "<td.*?>";
Pattern p = Pattern.compile(exp);
String s = "<td colspan=\"6\" class=\"pi\">05323111094ajsall look</td><td colspan=\"6\" class=\"pi\">05323111094ajsall look</td>";
Matcher matcher = p.matcher(s);
while (matcher.find()) {
String str = "";
String result = matcher.group();
int c = s.indexOf("colspan");
if (c != -1) {
str = " " + s.substring(c, c + 11);
}
s = s.replace(result , "<td" + str + ">");
}
System.out.println(s);
}
public static void main(String args[]) {
Test t = new Test();
t.PatternTest();
}
}
运行结果为:
<td colspan="6">05323111094ajsall look</td><td colspan="6">05323111094ajsall look</td>
exp 正则表达式,
Pattern p = Pattern.compile(exp);//编译正则表达式
Matcher matcher = p.matcher(s);//匹配字符串
matcher.find() //匹配结果,如果有匹配结果返回true,否则返回false
matcher.group() //返回匹配到的字符串