java轉義符和Regex轉義符,轉義符和

來源:互聯網
上載者:User

java轉義符和Regex轉義符,轉義符和

舉例來說,連續相同的3位元字的Regex的標準文法是:

 

([\d])\1{2}

但是如果在java代碼中這麼寫,就會出現語法錯誤,如下:

 

String regEx = "([\d])\1{2}";

考慮到\符號在java字串的文法中屬於轉義符,所以,需要的java的文法是:

 

String regEx = "([\\d])\\1{2}";

為了加深印象,再來看下一個例子:前面連續相同的3位元字,後面連續相同的三位字元的Regex的標準文法是:

 

(\d)\1{2}(.)\2{2}

而在java中,是這麼寫的:

 

String regEx = "(\\d)\\1{2}(.)\\2{2}";

注意,\1和\2指的是patten的位置。

最後給出整段測試代碼:

 

@Test
public void test02(){
    // 要驗證的字串
    String str = "111";
    // Regex規則
    String regEx = "([\\d])\\1{2}";
    //String regEx = "([\d])\1{2}";
    // 編譯Regex
    Pattern pattern = Pattern.compile(regEx);
    // 忽略大小寫寫法
    // Pattern pat = Pattern.compile(regEx, Pattern.CASE_INSENSITIVE);
    Matcher matcher = pattern.matcher(str);
    // 尋找字串中是否有匹配Regex的字元/字串
    boolean rs = matcher.find();
    System.out.println(rs);
}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.