標籤:調用 hang style 常用 bool bsp 子串 舉例 end
常用的Regex規則:
A:字元
x 字元 x。舉例:‘a‘表示字元a
\\ 反斜線字元。
\n 新行(換行)符 (‘\u000A‘)
\r 斷行符號符 (‘\u000D‘)
B:字元類
[abc] a、b 或 c(簡單類)
[^abc] 任何字元,除了 a、b 或 c(否定)
[a-zA-Z] a到 z 或 A到 Z,兩頭的字母包括在內(範圍)
[0-9] 0到9的字元都包括
C:預定義字元類
. 任何字元。我的就是.字元本身,怎麼表示呢? \.
\d 數字:[0-9]
\w 單詞字元:[a-zA-Z_0-9]
在Regex裡面組成單詞的東西必須有這些東西組成
D:邊界匹配器
^ 行的開頭
$ 行的結尾
\b 單詞邊界
就是不是單詞字元的地方。
舉例:hello world?haha;xixi
E:Greedy 數量詞
X? X,一次或一次也沒有
X* X,零次或多次
X+ X,一次或多次
X{n} X,恰好 n 次
X{n,} X,至少 n 次
X{n,m} X,至少 n 次,但是不超過 m 次
我有如下一個字串:"91 27 46 38 50"
請寫代碼實現最終輸出結果是:"27 38 46 50 9
分析:
A:定義一個字串
B:把字串進行分割,得到一個字串數組
C:把字串數組變換成int數組
D:對int數組排序
E:把排序後的int數組在組裝成一個字串
F:輸出字串
Demo: |
public class RegexTest { public static void main(String[] args) { // 定義一個字串 String s = "91 27 46 38 50"; // 把字串進行分割,得到一個字串數組 String[] strArray = s.split(" "); // 把字串數組變換成int數組 int[] arr = new int[strArray.length]; for (int x = 0; x < arr.length; x++) { arr[x] = Integer.parseInt(strArray[x]); } // 對int數組排序 Arrays.sort(arr); // 把排序後的int數組在組裝成一個字串 StringBuilder sb = new StringBuilder(); for (int x = 0; x < arr.length; x++) { sb.append(arr[x]).append(" "); } //轉化為字串 String result = sb.toString().trim(); //輸出字串 System.out.println("result:"+result); } } |
正則的替換功能:
String類的public String replaceAll(String regex,String replacement)
使用給定的 replacement 替換此字串所有匹配給定的Regex的子字串。
demo: |
public class RegexDemo { public static void main(String[] args) { // 定義一個字串 String s = "helloqq12345worldkh622112345678java"; // 我要去除所有的數字,用*給替換掉 // String regex = "\\d+"; // String regex = "\\d"; //String ss = "*"; // 直接把數字幹掉 String regex = "\\d+"; String ss = ""; String result = s.replaceAll(regex, ss); System.out.println(result); } } |
擷取下面這個字串中由三個字元組成的單詞
da jia ting wo shuo,jin tian yao xia yu,bu shang wan zi xi,gao xing bu?
demo: |
public class RegexDemo2 { public static void main(String[] args) { // 定義字串 String s = "da jia ting wo shuo,jin tian yao xia yu,bu shang wan zi xi,gao xing bu?"; // 規則 String regex = "\\b\\w{3}\\b"; // 把規則編譯成模式對象 Pattern p = Pattern.compile(regex); // 通過模式對象得到匹配器對象 Matcher m = p.matcher(s); // 調用匹配器對象的功能 // 通過find方法就是尋找有沒有滿足條件的子串 // public boolean find() // boolean flag = m.find(); // System.out.println(flag); // // 如何得到值呢? // // public String group() // String ss = m.group(); // System.out.println(ss); // // // 再來一次 // flag = m.find(); // System.out.println(flag); // ss = m.group(); // System.out.println(ss); while (m.find()) { System.out.println(m.group()); } // 注意:一定要先find(),然後才能group() // IllegalStateException: No match found // String ss = m.group(); // System.out.println(ss); } } |
java中Regex