<rt id="bn8ez"></rt>
<label id="bn8ez"></label>

  • <span id="bn8ez"></span>

    <label id="bn8ez"><meter id="bn8ez"></meter></label>

    隨筆-61  評論-159  文章-0  trackbacks-0
            最近深入看struts2的validation校驗框架,看到底層的很多的實現都用到正則表達式來實現。其中用得比較多的是兩個類,一個是java.util.regex.Matcher和java.util.regex.Pattern
            現在通過例子來說明:
            1、要求查找一段字符串里面相關匹配的字符串,然后根據要求奇偶大小寫替換。
            1、1先從不考慮奇偶考慮
    程序如下:
    1Pattern p = Pattern.compile("hello");
    2        Matcher m = p.matcher("hello Hello HELLo HeLLo HelLoworld HellOWORLD dafdasfadsf");
    3        
    4        while(m.find()){
    5            System.out.println(m.group());
    6        }

    7        System.out.println("----------------");
    8        System.out.println(m.replaceAll("HELLO"));
    輸出如下:
    hello
    ----------------
    HELLO Hello HELLo HeLLo HelLoworld HellOWORLD dafdasfadsf

    注:只有第一個hello是匹配的,所以打印出來只有一個hello
    *在JDK文檔中對Pattern的描述是:A compiled representation of a regular expression. 
    其中complie( )方法是把里面的字符串"hello"先編譯
    matcher( )方法就是把要校驗的字符串加載進來:

    matcher

    public Matcher matcher(CharSequence input)
    Creates a matcher that will match the given input against this pattern.
    Parameters:
    input - The character sequence to be matched
    Returns:
    A new matcher for this pattern

    **Matcher在JDK文檔里面描述是:

    An engine that performs match operations on a character sequence by interpreting a Pattern.

    A matcher is created from a pattern by invoking the pattern's matcher method. Once created, a matcher can be used to perform three different kinds of match operations:

    注:(英文通俗易懂就不翻譯了)
    ***其中replaceAll方法是替換字符串里面符合“hello”的字符串     
    源碼為:
     
     1public String replaceAll(String replacement) {
     2        reset();
     3        boolean result = find();
     4        if (result) {
     5            StringBuffer sb = new StringBuffer();
     6            do {
     7                appendReplacement(sb, replacement);
     8                result = find();
     9            }
     while (result);
    10            appendTail(sb);
    11            return sb.toString();
    12        }

    13        return text.toString();
    14    }
    --------------------------------------------------------------------------------------
    1、2下面對1、1中實現所有替換所有符合的字符串程序進行重構
    源碼如下:
     1Pattern p = Pattern.compile("hello",Pattern.CASE_INSENSITIVE);
     2        Matcher m = p.matcher("hello Hello HELLo HeLLo HelLoworld HellOWORLD dafdasfadsf");
     3        StringBuffer sb= new StringBuffer();
     4        int i = 0;
     5        while(m.find())
     6        {
     7            i++;
     8            if(i%2 == 0)
     9            {
    10                m.appendReplacement(sb, "hello");
    11            }
    else{
    12                m.appendReplacement(sb, "HELLO");
    13            }

    14            
    15        }

    16        m.appendTail(sb);
    17        System.out.println(sb);
    控制臺輸出:
    HELLO hello HELLO hello HELLOworld helloWORLD dafdasfadsf
    第1行中的Pattern.CASE_INSENSITIVE是忽略字母大小寫
    其中第5----13行加入就奇偶判斷
    appendReplacement就是把替換后的字符串放進StringBuffer的引用里面
    源碼為:
     1public Matcher appendReplacement(StringBuffer sb, String replacement) {
     2
     3        // If no match, return error
     4        if (first < 0)
     5            throw new IllegalStateException("No match available");
     6
     7        // Process substitution string to replace group references with groups
     8        int cursor = 0;
     9        String s = replacement;
    10        StringBuffer result = new StringBuffer();
    11
    12        while (cursor < replacement.length()) {
    13            char nextChar = replacement.charAt(cursor);
    14            if (nextChar == '\\'{
    15                cursor++;
    16                nextChar = replacement.charAt(cursor);
    17                result.append(nextChar);
    18                cursor++;
    19            }
     else if (nextChar == '$'{
    20                // Skip past $
    21                cursor++;
    22
    23                // The first number is always a group
    24                int refNum = (int)replacement.charAt(cursor) - '0';
    25                if ((refNum < 0)||(refNum > 9))
    26                    throw new IllegalArgumentException(
    27                        "Illegal group reference");
    28                cursor++;
    29
    30                // Capture the largest legal group string
    31                boolean done = false;
    32                while (!done) {
    33                    if (cursor >= replacement.length()) {
    34                        break;
    35                    }

    36                    int nextDigit = replacement.charAt(cursor) - '0';
    37                    if ((nextDigit < 0)||(nextDigit > 9)) // not a number
    38                        break;
    39                    }

    40                    int newRefNum = (refNum * 10+ nextDigit;
    41                    if (groupCount() < newRefNum) {
    42                        done = true;
    43                    }
     else {
    44                        refNum = newRefNum;
    45                        cursor++;
    46                    }

    47                }

    48
    49                // Append group
    50                if (group(refNum) != null)
    51                    result.append(group(refNum));
    52            }
     else {
    53                result.append(nextChar);
    54                cursor++;
    55            }

    56        }

    57
    58        // Append the intervening text
    59        sb.append(getSubSequence(lastAppendPosition, first));
    60        // Append the match substitution
    61        sb.append(result.toString());
    62
    63        lastAppendPosition = last;
    64    return this;
    65    }

    注:通過在java中使用正則表達式,可以很方便進行字符串校驗。
    附(例子):郵件格式校驗
    System.out.println("aa.a-aaa@163.com".matches("[\\w[.-]]+@[\\w[.-]]+\\.[\\w]+"));
    等價于以下代碼:
    Pattern pp = Pattern.compile("[\\w[.-]]+@[\\w[.-]]+\\.[\\w]+");
      Matcher m =pp.matcher("aa.a-aaa@163.com");
      System.out.println(m.matches());

    如果符合matches里面的校驗規則,則打印出true,否則是false。
    matches方法是String里面一個方法,看源碼實現
    1public boolean matches(String regex) {
    2        return Pattern.matches(regex, this);
    3    }


    1public static boolean matches(String regex, CharSequence input) {
    2        Pattern p = Pattern.compile(regex);
    3        Matcher m = p.matcher(input);
    4        return m.matches();
    5    }

    總結:深入一些框架的底層,其中很多校驗功能都是用到正則表達式,你會發覺使用正則表達式功能很強大。

    -------------------------------------------------------------------------------------------------
    PS:本博客文章,如果沒有注明是有“轉”字樣,屬于本人原創。如果需要轉載,務必注明作者文章的詳細出處地址,否則不允許轉載,多謝合作!
    posted on 2008-12-06 23:42 apple0668 閱讀(2545) 評論(0)  編輯  收藏 所屬分類: java
    主站蜘蛛池模板: 91在线视频免费播放| WWW国产亚洲精品久久麻豆| 亚洲第一综合天堂另类专| 99精品国产成人a∨免费看| 国产亚洲精品观看91在线| 免费人成视频在线观看免费| 日日夜夜精品免费视频| 亚洲精品成a人在线观看夫| 久久亚洲中文字幕精品一区| 免费福利在线观看| 666精品国产精品亚洲| 久久精品国产大片免费观看| 国产成人A亚洲精V品无码| 男女猛烈xx00免费视频试看| 亚洲成人影院在线观看| 特级毛片爽www免费版| 亚洲中文字幕无码不卡电影| 在线v片免费观看视频| 国产又黄又爽又大的免费视频| 亚洲欧洲无码AV电影在线观看| 麻豆精品不卡国产免费看| 亚洲人成网www| 免费精品国产自产拍在| 亚洲AV无码之国产精品| JLZZJLZZ亚洲乱熟无码| 免费人成在线观看网站| 国产成人亚洲综合a∨| 亚洲xxxxxx| 亚洲国产天堂久久综合| 午夜视频免费在线观看| 狠狠色伊人亚洲综合网站色| 免费网站看v片在线香蕉| 又大又硬又粗又黄的视频免费看| 亚洲国产成人久久精品app| 日韩一区二区三区免费体验| 中文字幕在线免费| 自拍偷自拍亚洲精品偷一| 亚洲国产精品综合一区在线| 亚洲Av无码乱码在线znlu| 成年性生交大片免费看| 午夜亚洲乱码伦小说区69堂|