標籤:ora article text 簡單 tar integer tutorial new 類型
做CC時經常要用Regex過濾資料,當時洗的資料比較複雜,規則比較多。這次做leetcode,複習一下Java的正則匹配。Leetcode 537. Complex Number Multiplication 從表示複數的字串裡把實部和虛部取出來。
http://blog.csdn.net/yin380697242/article/details/52049999
Pattern類,建構函式是私人類型,不能通過new建立,要通過Pattern.compile()獲得一個匹配模式。Pattern類可以進行簡單的匹配,如字串的分割,整個字串的匹配。
Matcher類,通過Pattern.matcher(string)獲得Matcher對象。matcher.find()方法,嘗試在輸入字串裡進行下一次匹配,每做一次匹配後m.start()和m.end()都會改變。
Greedy/Reluctant/Possessive https://docs.oracle.com/javase/tutorial/essential/regex/quant.html
Greedy模式如X? 首先嘗試匹配整個字串,若沒找到匹配,則退掉字串最後一個字元,重新嘗試匹配。
Reluctant模式如X?? 首先從字串頭開始匹配,若沒找到匹配,每次加一個字元,重新匹配。
Possesive模式如X?+ 嘗試匹配整個字串,若沒找到匹配,直接返回結果。
例子:
Enter your regex: .*foo // greedy quantifierEnter input string to search: xfooxxxxxxfooI found the text "xfooxxxxxxfoo" starting at index 0 and ending at index 13.Enter your regex: .*?foo // reluctant quantifierEnter input string to search: xfooxxxxxxfooI found the text "xfoo" starting at index 0 and ending at index 4.I found the text "xxxxxxfoo" starting at index 4 and ending at index 13.Enter your regex: .*+foo // possessive quantifierEnter input string to search: xfooxxxxxxfooNo match found.
*, ?, +的區別
*和?都可以匹配0個或多個,存在zero-length匹配,而+匹配時至少存在一個
Enter your regex: a?Enter input string to search: aI found the text "a" starting at index 0 and ending at index 1.I found the text "" starting at index 1 and ending at index 1.Enter your regex: a*Enter input string to search: aI found the text "a" starting at index 0 and ending at index 1.I found the text "" starting at index 1 and ending at index 1.Enter your regex: a+Enter input string to search: aI found the text "a" starting at index 0 and ending at index 1.
*和? 的區別
在下面的情況中,對?匹配了多次,而*匹配了最長的一次。
Enter your regex: a?Enter input string to search: aaaaaI found the text "a" starting at index 0 and ending at index 1.I found the text "a" starting at index 1 and ending at index 2.I found the text "a" starting at index 2 and ending at index 3.I found the text "a" starting at index 3 and ending at index 4.I found the text "a" starting at index 4 and ending at index 5.I found the text "" starting at index 5 and ending at index 5.Enter your regex: a*Enter input string to search: aaaaaI found the text "aaaaa" starting at index 0 and ending at index 5.I found the text "" starting at index 5 and ending at index 5.Enter your regex: a+Enter input string to search: aaaaaI found the text "aaaaa" starting at index 0 and ending at index 5.
這道Leetcode取實部和虛部的辦法:
int[] extractOp(String complex) { Pattern p = Pattern.compile("([-0-9]*)\\+([-0-9]*)i"); Matcher m = p.matcher(complex); String tmp; int[] re = new int[2]; while(m.find()) { tmp = m.group(1); if (tmp.startsWith("-")) { re[0] = -(int)Integer.valueOf(tmp.substring(1,tmp.length())); } else { re[0] = Integer.valueOf(tmp); } tmp = m.group(2); if (tmp.startsWith("-")) { re[1] = -(int)Integer.valueOf(tmp.substring(1,tmp.length())); } else { re[1] = Integer.valueOf(tmp); } } return re; }
4-30 Java正則匹配