关于正则式的概念、作用以及基础知识,这里就不多讲啦,这里给出两类实例供大家参考。其一是使用第三方包,其二是使用java API进行操作。本篇先给出第一类的实例,这里使用jakarta-oro.jar,这个包大家可以到网上down,然后添加到过程中即可。
*********************************************************************************************
//1、匹配服务器日志里德IP和时间
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package hfut.wst.regExp;
import org.apache.oro.text.regex.MatchResult;
import org.apache.oro.text.regex.Pattern;
import org.apache.oro.text.regex.PatternCompiler;
import org.apache.oro.text.regex.PatternMatcher;
import org.apache.oro.text.regex.Perl5Compiler;
import org.apache.oro.text.regex.Perl5Matcher;
/**
*
* @author Administrator
*/
public class regularExpressionTest {
public static void main(String[] args) {
String logEntry = "192.168.1.1 - - [11/September/2010:10:17:30 -0500]"
+ "\"GET /IsAlive.htm HTTP/1.0\" 200 15";
String regExp = "([0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3})\\s-\\s-\\s\\[([^\\]]+)\\]";
try {
PatternCompiler compiler = new Perl5Compiler();
Pattern pattern = compiler.compile(regExp);
PatternMatcher matcher = new Perl5Matcher();
if(matcher.contains(logEntry, pattern)){
MatchResult result = matcher.getMatch();
System.out.println(" IP:"+result.group(1));
System.out.println(" Date:"+result.group(2));
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
*********************************************************************************************
//匹配html font标签及其属性
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package hfut.wst.regExp;
import org.apache.oro.text.regex.MatchResult;
import org.apache.oro.text.regex.Pattern;
import org.apache.oro.text.regex.PatternCompiler;
import org.apache.oro.text.regex.PatternMatcher;
import org.apache.oro.text.regex.PatternMatcherInput;
import org.apache.oro.text.regex.Perl5Compiler;
import org.apache.oro.text.regex.Perl5Matcher;
/**
*
* @author Administrator
*/
public class regExpForHtmlFont {
public static void main(String[] args) {
String html = "<font face=\"Arial, Serif\" size=\"+2\" color=\"red\">";
String regExpForTag = "<\\s*font\\s+([^>]*)\\s*>";
String regExpForAttr = "([a-z]+)\\s*=\\s*\"([^\"]+)\"";
try {
PatternCompiler compiler = new Perl5Compiler();
Pattern patternForTag = compiler.compile(regExpForTag, Perl5Compiler.CASE_INSENSITIVE_MASK);
Pattern patternForAttr = compiler.compile(regExpForAttr, Perl5Compiler.CASE_INSENSITIVE_MASK);
PatternMatcher matcher = new Perl5Matcher();
if(matcher.contains(html, patternForTag)){
MatchResult result = matcher.getMatch();
String attr = result.group(1);
System.out.println("Hello, Match Successfully!!");
System.out.println(attr);
PatternMatcherInput input = new PatternMatcherInput(attr);
while(matcher.contains(input, patternForAttr)){
MatchResult resultTemp = matcher.getMatch();
System.out.println(resultTemp.group(1)+"="+resultTemp.group(2));
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}