Jafe Lee

            BlogJava :: 首頁 :: 新隨筆 :: 聯系 :: 聚合  :: 管理 ::
            49 隨筆 :: 0 文章 :: 24 評論 :: 0 Trackbacks
          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并執行匹配、查找工作的類,跟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
          主站蜘蛛池模板: 麦盖提县| 临颍县| 芒康县| 洞头县| 禹城市| 无为县| 廊坊市| 西平县| 安福县| 沐川县| 尚义县| 谷城县| 宜春市| 河曲县| 长泰县| 宁津县| 彭山县| 潼南县| 灵武市| 泸水县| 汉中市| 康乐县| 拉萨市| 凭祥市| 舞阳县| 建湖县| 安吉县| 仪征市| 石渠县| 嘉荫县| 成安县| 贺州市| 四平市| 固原市| 临安市| 瑞昌市| 黄陵县| 常熟市| 城口县| 新疆| 比如县|