Jafe Lee

            BlogJava :: 首頁 :: 新隨筆 :: 聯系 :: 聚合  :: 管理 ::
            49 隨筆 :: 0 文章 :: 24 評論 :: 0 Trackbacks
          <2007年12月>
          2526272829301
          2345678
          9101112131415
          16171819202122
          23242526272829
          303112345

          常用鏈接

          留言簿(5)

          隨筆分類(50)

          隨筆檔案(46)

          文章分類

          搜索

          最新評論

          評論排行榜

          1、Java 1.4之后的版本引進了一個用于處理正則表達式的包 java.util.regex.*; 該包主要包含三個類:
          • Pattern : 用來表示一個經過編譯處理后的正則表達式。通俗一點來說,就是用一個類來表示一個正則表達式,這個類是從正則表達式構造得到的。這個類并沒有public constructor, 如果想得到一個這個類的一個對象則必須調用該類的public static方法:public static Pattern compile(String regex)或者 public static Pattern compile(String regex,int flags)。這兩個方法返回一個Pattern型的對象。
          • Matcher : 解釋Pattern并執(zhí)行匹配、查找工作的類,跟Pattern類一樣,這個類也沒有定義public constructor,要想獲得一個Matcher對象必須調用Pattern類的方法 public Matcher matcher(CharSequence input) 來得到。
          • PatternSyntaxException : 一個unchecked exception。當遇到不符和Java正則表達式的語法的時候程序就會拋出這個異常。
          2、一個例子(摘自java.sun.com
          package?regex;

          import
          ?java.io.Console;
          import?java.util.regex.Pattern;
          import?java.util.regex.Matcher;

          public?class?RegexTestHarness?{
          ????
          public?static?void?main(String?[]?args)?{
          ????????Console?console?
          =?System.console();
          ????????
          if?(console?==?null)?{
          ????????????System.err.println(
          "No?console.");
          ????????????System.exit(
          1);
          ????????}
          ????????
          while?(true)?{
          ????????????Pattern?pattern?
          =?Pattern.compile(console.readLine("%nEnter?your?regex:?"));
          ????????????Matcher?matcher?
          =?pattern.matcher(console.readLine("Enter?input?string?to?search:?"));
          ????????????
          boolean?found?=?false;
          ????????????
          while?(matcher.find())?{
          ????????????????console.format(
          "I?found?the?text?\"%s\"starting?at?"?+
          ????????????????????????
          "index?%d?and?ending?at?index?%d.?%n",?matcher.group(),?matcher.start(),?matcher.end());
          ????????????????found?
          =?true;
          ????????????}
          ????????????
          if?(!found)
          ????????????????console.format(
          "No?match?found.%n");
          ????????}
          ????}
          }
          注:由于這個例子使用了JDK 1.6后才有的方法:System.console(),所以這個例子在eclipse和netbeans都不能正常運行。只有在命令行下才能正確運行。如果想在eclipse和nb下運行,好像可以用System.out/in來代替System.console。
          posted on 2007-12-09 19:47 Jafe Lee 閱讀(921) 評論(0)  編輯  收藏 所屬分類: Java
          主站蜘蛛池模板: 桓台县| 阳原县| 闽清县| 广州市| 河津市| 泰州市| 民县| 白山市| 弋阳县| 息烽县| 汉沽区| 西城区| 金山区| 苍南县| 左权县| 哈尔滨市| 十堰市| 江源县| 精河县| 易门县| 霍邱县| 同心县| 登封市| 杭锦后旗| 会理县| 那坡县| 江孜县| 泰和县| 昭苏县| 临清市| 阿城市| 通许县| 伊通| 灵石县| 洛宁县| 宜昌市| 习水县| 台江县| 营山县| 萨迦县| 黎平县|