標籤: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使用