大綱:
- 語法
- 實戰
- 反向引用、替換
一、語法
捕獲組:匹配子表達式內容,匹配結果以編號或顯示命名的方式存在內存,可供正則本身,也可供替換使用。
語法:
- 數字編號(pattern),匹配結果保存為數字。
- 顯示命名(?<name>pattern),匹配結果保存到變量name中。
- 非捕獲(?:pattern),標識不需要保存的組。
二、實戰
文本:1990-10-10
文本為一個日期,需要分別找出年、月、日。
2.1數字編號:
public static void main(String[] args) { String pattern = "(\\d+)-(\\d+)-(\\d+)"; String word = "1990-10-14"; final Pattern compile = Pattern.compile(pattern); final Matcher matcher = compile.matcher(word); if(matcher.find()){ final int i = matcher.groupCount(); System.out.println("共"+i+"組"); for (int j = 0; j <= i; j++) { System.out.println("第"+j+"組:"+matcher.group(j)); } } } /** * 共3組 * 第0組:1990-10-10 * 第1組:1990 * 第2組:10 * 第3組:14 */
第0組為整個表達式匹配內容,剩下每組對應一個括號,順延下去。
2.2顯示命名:
public static void main(String[] args) { String pattern = "(?<nian>\\d+)-(?<yue>\\d+)-(?<ri>\\d+)"; String word = "1990-10-14"; final Pattern compile = Pattern.compile(pattern); final Matcher matcher = compile.matcher(word); if(matcher.find()){ final int i = matcher.groupCount(); System.out.println("共"+i+"組"); System.out.println("年:"+matcher.group("nian")); System.out.println("月:"+matcher.group("yue")); System.out.println("日:"+matcher.group("ri")); } } /** * 共3組 * 年:1990 * 月:10 * 日:14 */
3.3非捕獲組
public static void main(String[] args) { String pattern = "(?:\\d+)-(\\d+)-(\\d+)"; String word = "1990-10-14"; final Pattern compile = Pattern.compile(pattern); final Matcher matcher = compile.matcher(word); if(matcher.find()){ final int i = matcher.groupCount(); System.out.println("共"+i+"組"); for (int j = 0; j <= i; j++) { System.out.println("第"+j+"組:"+matcher.group(j)); } } } /** * 共2組 * 第0組:1990-10-14 * 第1組:10 * 第2組:14 */
如果年這一組我們不需要,我們就可以通過非捕獲來排除它。
三、反向引用、替換
3.1在正則本身中使用捕獲到的組就是反向引用
\數字編號 或 \k<顯示命名>
例子:
找出重復字母
用\k<顯示命名>
public static void main(String[] args) { String pattern = "(?<chongfu>\\w)\\k<chongfu>+"; String word = "aaabbcdddde"; final Pattern compile = Pattern.compile(pattern); final Matcher matcher = compile.matcher(word); while(matcher.find()){ System.out.println(matcher.group()); } } /** * aaa * bb * dddd */
用\數字編號>
public static void main(String[] args) { String pattern = "(\\w)\\1+"; String word = "aaabbcdddde"; final Pattern compile = Pattern.compile(pattern); final Matcher matcher = compile.matcher(word); while(matcher.find()){ System.out.println(matcher.group()); } } /** * aaa * bb * dddd */
3.2替換
替換用 $組號 表示
例子
把所有重復字母替換成不重復的
public static void main(String[] args) { String word = "aaabbcdddde"; System.out.println(word.replaceAll("(\\w)\\1+", "$1")); } /** * abcde */