public static void main(String[] args) {
String regex = "http://www.youtube.com/channel/(\\w+)\\?feature";
String str="http://www.youtube.com/channel/UCgYQrFwjImpTQbovggoCLlg?feature=watch";
Pattern p = Pattern.compile(regex, Pattern.DOTALL | Pattern.CASE_INSENSITIVE);
Matcher matcher = p.matcher(str);
while (matcher.find()) {
for(int i = 0; i <= matcher.groupCount(); i++) {
String mat = matcher.group(i);
System.out.println(mat);
}
}
}
打印出结果
http://www.youtube.com/channel/UCgYQrFwjImpTQbovggoCLlg?feature
UCgYQrFwjImpTQbovggoCLlg
原字符串是http://www.youtube.com/channel/UCgYQrFwjImpTQbovggoCLlg?feature=watch
正则表达式http://www.youtube.com/channel/(\\w+)\\?feature
group(0)是http://www.youtube.com/channel/UCgYQrFwjImpTQbovggoCLlg?feature
group(1)是UCgYQrFwjImpTQbovggoCLlg
group(0)是整个正则表达式对应的字符串,group(1)是第一个括号里正则表达式中对应的字符串,group(n)是第n-1个括号里正则表达式中对应的字符串