Scanner定界符與使用正則表達式掃描

  Scanner定界符與使用正則表達式掃描
  import java.util.Scanner; import java.util.regex.MatchResult; /** * @author clydelou * */ public class ScannerDelimiter { /** * @param args */ static String threatData = "58.27.82.161@02/10/2005\n" + "204.45.234.40@02/11/2005\n" + "58.27.82.161@02/11/2005\n" + "58.27.82.161@02/12/2005\n" + "58.27.82.161@02/13/2005\n" + "[next log section with different data format]"; public static void main(String[] args) { // TODO Auto-generated method stub Scanner scanner = new Scanner("12, 42,78,99,42");// 默認情況下,Scanner根據空白字符對輸入進行分詞,但是你可以用正則表達式指定自己所需的定界符 scanner.useDelimiter("\\s*,\\s*");// 使用逗號(包括逗號前後任意的空白字符)作爲定界符 System.out.println(scanner.delimiter());// 使用delimiter()方法用來返回當前正在作爲定界符的Pattern對象 while (scanner.hasNextInt()) System.out.print(scanner.nextInt() + "\t"); System.out.println(); // 使用正則表達式掃描 // 當next()方法配合指定的正則表達式使用時,將找到下一個匹配該模式的輸入部分,調用match()方法就可以獲得匹配結果. // 注意:在配合正則表達式使用掃描時,它僅僅針對下一個輸入分詞進行匹配,如果正則表達式中含有界定符,那永遠都不可能匹配成功. scanner = new Scanner(threatData); String pattern = "(\\d+[.]\\d+[.]+\\d+[.]\\d+)@" + "(\\d{2}/\\d{2}/\\d{4})"; // Capturing groups are indexed from left to right, starting at one. // Group zero denotes the entire pattern, so the expression m.group(0) // is equivalent to m.group(). // Groups and capturing // // Capturing groups are numbered by counting their opening parentheses // from left to right. In the expression ((A)(B(C))), for example, there // are four such groups: // // 1 ((A)(B(C))) // 2 (A) // 3 (B(C)) // 4 (C) // // Group zero always stands for the entire expression. // // Capturing groups are so named because, during a match, each // subsequence of the input sequence that matches such a group is saved. // The captured subsequence may be used later in the expression, via a // back reference, and may also be retrieved from the matcher once the // match operation is complete. // // The captured input associated with a group is always the subsequence // that the group most recently matched. If a group is evaluated a // second time because of quantification then its previously-captured // value, if any, will be retained if the second evaluation fails. // Matching the string "aba" against the expression (a(b)?)+, for // example, leaves group two set to "b". All captured input is discarded // at the beginning of each match. // // Groups beginning with (? are pure, non-capturing groups that do not // capture text and do not count towards the group total. // 組(Groups)是用括號劃分的正則表達式,可以根據組的標號來引用某個組.組號爲0表示整個表達式,組號1表示被第一對括號括起來的組,依此類推. while (scanner.hasNext(pattern)) { scanner.next(pattern); MatchResult match = scanner.match(); String ip = match.group(1); String date = match.group(2); System.out.format("Threat on %s from %s\n", date, ip); } } }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章