javaRegex

來源:互聯網
上載者:User

標籤:eal   編程   運算式   並集   font   greedy   擷取的群組   字元   ring   

1, [abc] a, b 或 c

       [^abc] 任何字元,除了a,b 或 c

  [a-zA-Z] a 到 z 或 A 到 Z,兩頭字元都包括在內

  [a-d[m-p]] a 到 d 或 m 到 p :[a-dm-p](並集)

  [a-z&&[def]] d,e 或 f(交集)

2, * 任何字元

  \d 數字: [0-9]

  \D 非數字:[^0-9]

  \s 空白字元:[\t\n\x0B\f\r]

  \S 非空白字元:[^\s]

  \w 單詞字元:[a-zA-Z_0-9]

  \W 非單詞字元:[^\w]

3, Greedy 數量詞

  X?  一次或一次也沒有

  X*  零次或多次

  X+  一次或多次

  X{n}  恰好n次

  X{n,}  至少n次

  X{n,m}  至少n次,但是不超過m次字串

4, 替換功能

  String s = "Hello123World";

  String regex = "\\d";

  String s2 = s.replaceAll(regex, "");

5,  分組功能

  擷取的群組可以通過從左至右計算其開括弧來編號,((A)(B(C)))存在4個這樣的組

  1  ((A)(B(C)))

  2  (A)

  3  (B(C))

  4    (C)

  應用:疊詞切割:"sdqqfgkkkhjppppkl";

  String regex = "(.)\\1+"; String[] arr = s.split(regex);

  應用:把字串"我我....我...我.我...要要...要學....學學..學.編.編編.編.程...程程...程"輸出為"我要學編程"

  String s = "我我....我...我.我...要要...要學....學學..學.編.編編.編.程...程程...程";

  String s2 = s.replaceAll("\\.+", "");

  String s3 = s2.replaceAll("(.)\\1+", "$1");

6, Pattern和Matcher

  Pattern p = Pattern.compile(a*b);  //擷取到Regex

  Matcher m = p.matcher("aaaaaab");  //擷取匹配器

  boolean b = m.matches();  //看是否能匹配,匹配就返回true

   等價於System.out.println("aaaaaab".matches("a*b"));

  應用:擷取字串中的電話號碼

  String s = "我的電話號碼是18988888888,曾經用過18987654321,還用過18812345678";

  String regex = "1[3578]\\d{9}";

  Pattern p = Pattern.compile(regex);

  Matcher m = p.matcher(s);

  while(m.find()) System.out.println(m.group()); //必須先find再group

javaRegex

聯繫我們

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