javaRegex使用

來源:互聯網
上載者:User

標籤:ati   sys   ring   完全   開發   表達   項目   pre   十分   

用Regex進行字串校正,截取十分方便,項目開發中靈活的使用Regex能讓你的代碼簡潔優雅並且不易出錯。在實際的應用中,掌握以下幾點知識就可以應付絕大多數的開發情境了。

1、 字串開始結束匹配:^$。

^abc$完全符合字串abc。

2、 特定類型字元匹配:數字\d,數字字母底線\w,空格\s,任一字元.。

3、 重複匹配:重複0次或1次?,重複1次及以上+,重複0次及以上*,重複m到n次{m,n},重複m次以上{m,}。

\d+標識有一個或多個數字組成的字串,比如0,10,110。

4、 單個字元或[],|。

[ab]表示a或b,a|b表示a或b。

5、 字串或(|)。

(ab|bc)表示ab或者bc。

6、 非[^]。

[^a]表示不是a的一個字元;[^ab]表示不是a且不是b的一個字元;[^ab]+表示一個或多個字元,且每個字元都不是a或b。

 

Java中,String.matches(regex)進行字串Regex校正;String.replaceAll()進行Regex替換;Pattern,Matcher則可以進行Regex匹配,尋找,替換等一系列操作。下面是代碼執行個體:

package com.coshaho.learn.reg;import java.util.regex.Matcher;import java.util.regex.Pattern;public class RegexTest {public static void main(String[] args){// 重複String regex = "^\\s*\\d+{1,3}\\w+ .?$";String str = "  110hkx_ @";System.out.println(str.matches(regex));// 字元或regex = "^[abc]$"; // 等價於^a|b|c$str = "b";System.out.println(str.matches(regex));// 字串或regex = "^(ab|cd)$";str = "ab";System.out.println(str.matches(regex));// 非regex = "^[^abc]$";str = "d";System.out.println(str.matches(regex));regex = "\\[([^\\[\\]]+)\\]\\.\\[([^\\[\\]]+)\\]";str = "[device].[cpu] + [interface].[tranffic] >= 2";Pattern pattern = Pattern.compile(regex);Matcher matcher = pattern.matcher(str);while(matcher.find()){System.out.println(matcher.group());if(2 == matcher.groupCount()){System.out.println(matcher.group(1));System.out.println(matcher.group(2));}}regex = "\\d+";str = "abc123def456hijk789xyz";System.out.println(str.replaceAll(regex, " "));}}/**輸出值truetruetruetrue[device].[cpu]devicecpu[interface].[tranffic]interfacetranfficabc def hijk xyz**/

  

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.