javaRegex學習筆記之命名捕獲_java

來源:互聯網
上載者:User

很多正則引擎都支援命名分組,java是在java7中才引入這個特性,文法與.Net類似(.Net允許同一運算式出現名字相同的分組,java不允許)。
命名分組很好理解,就是給分組進行命名。下面簡單示範一下java中如何使用以及注意事項。

1.正則中定義名為NAME的分組
(?<NAME>X)
這裡X為我們要匹配的內容,注意,在這個命名不能重複,名字也不能以數字開頭!

2.反向引用NAME組所匹配到的內容
\k<NAME>
注意,反向引用是針對組所匹配到的內容,而非組的運算式。

3.替換中,引用組NAME中捕獲到的字串
${NAME}

4.擷取NAME組捕獲的字串
group(String NAME)
注意:也可以使用序號對命名捕獲進行引用,序號從1開始,0為正則的完整匹配結果。

下面用一個簡單的正則來分別擷取年月日為例:

String s = "2015-10-26"; Pattern p = Pattern.compile("(?<year>\\d{4})-(?<month>\\d{2})-(?<day>\\d{2})"); Matcher m = p.matcher(s); if (m.find()) {   System.out.println("year: " + m.group("year")); //年   System.out.println("month: " + m.group("month")); //月   System.out.println("day: " + m.group("day")); //日       System.out.println("year: " + m.group(1)); //第一組   System.out.println("month: " + m.group(2)); //第二組   System.out.println("day: " + m.group(3)); //第三組 }  System.out.println(s.replaceAll("(?<year>\\d{4})-(?<month>\\d{2})-(?<day>\\d{2})", "${day}-${month}-${year}")); //將 年-月-日 形式的日期改為 日-月-年 形式 

輸出結果

year: 2015month: 10day: 26year: 2015month: 10day: 2626-10-2015

以上就是本文的全部內容,希望對大家的學習有所協助。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.