正則的具體寫法不是重點,一般常用的還是比較簡單的
主要想說的是在JAVA裡使用正則的幾種情況
先來定義兩個變量:
1、被查找的字元串:str
2、要查找的關鍵字(或正規表達式):keywordPattern
情況一:判斷str裡是否含有keywordPattern
1 import java.util.regex.Matcher;
2 import java.util.regex.Pattern;
3
4 public class RegTest {
5 public static void main(String[] args) {
6 String str = "我是人。。我是好人。。我是好男人。。- - !!";
7 Pattern keywordPattern = Pattern.compile("好男人");
8 Matcher matcher = keywordPattern.matcher(str);
9 System.out.println(str.find());
10 }
11 }
輸出:true
情況二:判斷str是否完全符合keywordPattern,可用于郵箱驗證等情況
1 public class RegTest {
2 public static void main(String[] args) {
3 String str = "abcd1234ABCD";
4 Pattern keywordPattern = Pattern.compile("^[a-zA-Z0-9]+$");
5 Matcher matcher = keywordPattern.matcher(str);
6
7 System.out.println(matcher.matches());
8 //System.out.println(matcher.find()); 也可以實作同樣的效果
9 }
10 }
情況三:将str中符合keywordPattern的字元都替換掉
6 String str = "abcd1234ABCD";
7 Pattern keywordPattern = Pattern.compile("[0-9]");
9
10 System.out.println(matcher.replaceAll("@"));
11 }
12 }
輸出:
abcd@@@@ABCD情況四:将str中符合keywordPattern的字元替換掉一部分,某些被替換的字元還需保留
6 String str = "12[3]456[7]890";
7 Pattern keywordPattern = Pattern.compile("\\[(\\d)\\]");
10 System.out.println(matcher.replaceAll("<$1>"));
輸出:12<3>456<7>890
情況五:将str中符合keywordPattern的字元替換掉一部分,某些被替換的字元還需做為參數進行處理
1 import java.util.regex.Matcher;
2 import java.util.regex.Pattern;
3
4 public class RegTest {
5 public static void main(String[] args) {
6 String str = "a[b]cdef[g]hij[k]lmn";
7 Pattern keywordPattern = Pattern.compile("\\[([a-z])\\]");
8 Matcher matcher = keywordPattern.matcher(str);
9
10 StringBuffer strB = new StringBuffer();
11 while(matcher.find()){
12 matcher.appendReplacement(strB, getChar(matcher.group(1)));
13 }
14 matcher.appendTail(strB);
15 System.out.print(strB.toString());
16 }
17
18 public static String getChar(String num){
19 return "[" + num.toUpperCase() + "]";
20 }
21 }
輸出:a[B]cdef[G]hij[K]lmn
其中第四和第五兩種方法,可以實作 公式解析 和 模闆解析 等複雜功能。
寵辱不驚,看庭前花開花落;去留無意,望天上雲卷雲舒