几个原则:
分组的编号从1开始
遇到()加1
遇到断言跳过,如(?:exp)这种格式的,如果要算的话就,((?:exp))
package cn.yuhui.com;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegexUtil {
public static void main(String[] args) {
String str = "219.133.40.15 - - [20/Apr/2016:07:00:01 +0800] \"GET /RSS2.xml HTTP/1.1\" 200 10664 \"-\" \"Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN; rv:1.9b4) Gecko/2008030317 Firefox/3.0b4\" -";
RegexUtil.Match(str,"(\\d+\\.\\d+\\.\\d+\\.\\d+)\\s(\\S.*?)\\s(\\S.*?)\\s\\[(\\S.*?)\\]\\s\\s\"(\\S.*?)\\s(\\S.*?)\\s(\\S.*?)\"\\s(\\S.*?)\\s(\\S.*?)\\s\"\\-\"\\s\"(\\S.*?)\"");
}
/**
*
* 正则表达式辅助类
*
* @param input 字符串
* @param regex 正则表达式
* @return 正则表达式匹配结果第一条
*/
public static void Match(String input,String regex) {
Pattern praiseCompile = Pattern.compile(regex);
Matcher praiseMatcher = praiseCompile.matcher(input);
int num = praiseMatcher.groupCount();
while (praiseMatcher.find()) {
System.out.println( praiseMatcher.group());
for(int i = 1 ; i<=num ; i++){
System.out.println( "praiseMatcher.group("+i+")------>"+praiseMatcher.group(i));
}
}
}
}
运行结果: