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

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

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

    隨筆-61  評(píng)論-159  文章-0  trackbacks-0
            最近深入看struts2的validation校驗(yàn)框架,看到底層的很多的實(shí)現(xiàn)都用到正則表達(dá)式來實(shí)現(xiàn)。其中用得比較多的是兩個(gè)類,一個(gè)是java.util.regex.Matcher和java.util.regex.Pattern
            現(xiàn)在通過例子來說明:
            1、要求查找一段字符串里面相關(guān)匹配的字符串,然后根據(jù)要求奇偶大小寫替換。
            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

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

    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下面對(duì)1、1中實(shí)現(xiàn)所有替換所有符合的字符串程序進(jìn)行重構(gòu)
    源碼如下:
     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);
    控制臺(tái)輸出:
    HELLO hello HELLO hello HELLOworld helloWORLD dafdasfadsf
    第1行中的Pattern.CASE_INSENSITIVE是忽略字母大小寫
    其中第5----13行加入就奇偶判斷
    appendReplacement就是把替換后的字符串放進(jìn)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中使用正則表達(dá)式,可以很方便進(jìn)行字符串校驗(yàn)。
    附(例子):郵件格式校驗(yàn)
    System.out.println("aa.a-aaa@163.com".matches("[\\w[.-]]+@[\\w[.-]]+\\.[\\w]+"));
    等價(jià)于以下代碼:
    Pattern pp = Pattern.compile("[\\w[.-]]+@[\\w[.-]]+\\.[\\w]+");
      Matcher m =pp.matcher("aa.a-aaa@163.com");
      System.out.println(m.matches());

    如果符合matches里面的校驗(yàn)規(guī)則,則打印出true,否則是false。
    matches方法是String里面一個(gè)方法,看源碼實(shí)現(xiàn)
    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    }

    總結(jié):深入一些框架的底層,其中很多校驗(yàn)功能都是用到正則表達(dá)式,你會(huì)發(fā)覺使用正則表達(dá)式功能很強(qiáng)大。

    -------------------------------------------------------------------------------------------------
    PS:本博客文章,如果沒有注明是有“轉(zhuǎn)”字樣,屬于本人原創(chuàng)。如果需要轉(zhuǎn)載,務(wù)必注明作者文章的詳細(xì)出處地址,否則不允許轉(zhuǎn)載,多謝合作!
    posted on 2008-12-06 23:42 apple0668 閱讀(2542) 評(píng)論(0)  編輯  收藏 所屬分類: java
    主站蜘蛛池模板: 免费人妻精品一区二区三区| 亚洲日产韩国一二三四区| 麻豆最新国产剧情AV原创免费| 一个人看的www免费视频在线观看| 一个人免费播放在线视频看片| 水蜜桃视频在线观看免费| 美女尿口扒开图片免费| 美女免费视频一区二区三区| 美女被暴羞羞免费视频| 一级做a爰黑人又硬又粗免费看51社区国产精品视 | 一本岛高清v不卡免费一三区| 亚洲免费观看网站| 91精品免费国产高清在线| 精品免费久久久久久久| 免费99精品国产自在现线| 免费无码AV电影在线观看| 拨牐拨牐x8免费| 又粗又硬又黄又爽的免费视频| 国产在线观看免费不卡 | 91九色视频无限观看免费| 久视频精品免费观看99| 国产麻豆视频免费观看| 成人一a毛片免费视频| 国产免费黄色大片| 亚洲一区二区视频在线观看| 亚洲人成无码网站| 激情内射亚洲一区二区三区| 亚洲导航深夜福利| 亚洲狠狠婷婷综合久久蜜芽| 国产亚洲漂亮白嫩美女在线| sihu国产精品永久免费| 久久精品免费观看国产| 中文字幕人成无码免费视频| 国产高清免费在线| 亚洲日韩小电影在线观看| 亚洲人成网www| 亚洲熟女乱色一区二区三区| 最新亚洲人成无码网站| 国产在线国偷精品免费看| 最近免费2019中文字幕大全| 在线免费观看a级片|