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

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

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

    javaGrowing

      BlogJava :: 首頁 :: 新隨筆 :: 聯系 :: 聚合  :: 管理 ::
      92 隨筆 :: 33 文章 :: 49 評論 :: 0 Trackbacks

    #

    The Document object is the root-node of a document. All nodes in a node-tree are childnodes of the Document object.


    Examples

    We will use the following XML document in the examples below: note.xml.

    documentElement - Return the node name of the root element

    createElement() - Create a new element

    createTextNode() - Create a new text node

    createCDATASection() - Create a new CDATA node

    createComment() - Create a new comment node

    getElementsByTagName() - Return the value of a specified node


    The Document object

    The Document object represents the entire XML document.

    The Document object is the root-node of a document. All nodes in a node-tree are childnodes of the Document object.

    A node can be an element node, an attribute node, a text node, or any other of the node types explained in the "Node types" chapter.

    IE: Internet Explorer, F: Firefox, N: Netscape, W3C: World Wide Web Consortium (Internet Standard)

    Document Object Properties

    Property Description IE F N W3C
    async Specifies whether downloading of an XML file should be handled asynchronously or not. True means that the load() method returns the control to the caller before the download is complete. False means that the download must be completed before the caller gets the control back 5 - - No
    attributes Returns a NamedNodeMap that contains all attributes of a node 5 1 6 No
    baseName Returns the name of a node (without namespaces) 5 - - No
    childNodes Returns a node list that contains all children of a node 5 1 6 No
    dataType Returns the data type of a node 5 - - No
    definition Returns the definition of a node in the DTD/Schema 5 - - No
    doctype Returns the DTD or Schema for the document 6 1 6 Yes
    documentElement Returns the root element of the document 5 1 6 Yes
    firstChild Returns the first child node of a node 5 1 6 No
    implementation Returns the DOMImplementation object for this particular document 6 1 6 Yes
    lastChild Returns the last child node of a node 5 - - No
    namespaceURI Returns the URI of the namespace 5 1 6 No
    nextSibling Returns the node immediately following a node. Two nodes are siblings if they have the same parent node 5 1 6 No
    nodeName Returns the name of the node 5 1 6 No
    nodeType Returns the node type as a number 5 1 6 No
    nodeTypedValue Returns the value of a node expressed in its defined data type 5 - - No
    nodeTypeString Returns the node type as a string 5 - - No
    nodeValue Returns the value of the node 5 1 6 No
    ownerDocument Returns the Document object of a node (returns the root node of the document) 5 1 6 No
    parentNode Returns the parent node of a node 5 1 6 No
    parsed Returns true if the node and all of its descendants have been parsed. Otherwise it returns false 5 - - No
    parseError Returns a ParseError object containing information about the parse error 5 - - No
    prefix Returns the namespace prefix of a node 5 - - No
    preserveWhiteSpace Returns true if the default processing preserves white space. Otherwise it returns false 5 - - No
    previousSibling Returns the node immediately previous to the current node. Two nodes are siblings if they have the same parent node 5 1 6 ?
    readyState Returns the current state of the XML document 5 - - No
    text Returns the text content of a node and all its children 5 - - No
    url Returns the URL for the last loaded XML document 5 - - No
    validateOnParse Indicates whether the document should be validated by the parser. Default is true. If false, only well-formed XML will be parsed 5 - - No
    xml Returns the XML of a node and all its children 5 - - No

    Document Object Methods

    Method Description IE F N W3C
    abort() Aborts the XML download 5 - - No
    appendChild("name") Appends a new childnode to a node 5 - - No
    cloneNode(boolean) Creates an exact clone node of a node. If the boolean parameter is set to true, the cloned node clones all the child nodes of the original node as well 5 - - No
    createAttribute("name") Creates a new attribute node 6 1 6 Yes
    createCDATASection("text") Creates a new CDATA section node 5 - - Yes
    createComment("text") Creates a new comment node 6 - - Yes
    createDocumentFragment() Creates an empty documentFragment object 5 1 6 Yes
    createElement("name") Creates a new element node 5 1 6 Yes
    createEntityReference("name") Creates a new entityReference node 5 - - Yes
    createNode(type,name,ns) Creates a new node 5 - - No
    createProcessingInstruction(target,text) Creates a new processingInstruction node 5 - - Yes
    createTextNode("text") Creates a new text node 5 1 6 Yes
    getElementById("id") ? 5 1 6 Yes
    getElementByName("name") ? 5 1 6 ?
    getElementsByTagName("name") Returns the specified node, and all its child nodes, as a node list 5 1 6 Yes
    hasChildNodes() Returns true if a node has child nodes. Otherwise it returns false 5 - - No
    insertBefore(newnode,refnode) Inserts a new node before an existing node 5 - - No
    load("URL") Loads the specified XML document 5 - - No
    loadXML("text") Loads an XML document using the specified string 5 - - No
    nodeFromID(id) Returns the node for the element whose ID attribute matches the one specified 5 - - No
    removeChild("name") Removes and returns the specified node 5 - - No
    replaceChild(newnode,oldnode) Replaces an oldnode with a newnode, and returns the oldnode 5 - - No
    save(obj) Saves an XML document to the specified location 5 - - No
    selectNodes(pattern) Creates a node list of all the matching descendant nodes returned by the specified pattern 5 - - No
    selectSingleNode(pattern) Returns a Node object for the first descendant node to match the specified pattern 5 - - No
    transformNode(stylesheet) Processes a node and its descendants using the specified XSL stylesheet, and returns the result 5 - - No
    transformNodeToObject(stylesheet,object) Processes a node and its descendants using the specified XSL stylesheet, and returns the result in the specified object 5 - - No

    Events

    Event Description IE F N W3C
    ondataavailable Executes some code when the XML document data is available

    Syntax: document.ondataavailable="myFunction"

    5 - - No
    onreadystatechange Executes some code when the readyState property changes

    Syntax: document.onreadystatechange="myFunction"

    5 - - No
    ontransformnode Triggered before each node in the XML is transformed by each node in the style sheet

    Syntax: boolean = ontransformnode(nodecode,nodedata)

    5 - - No
    posted @ 2006-08-01 09:28 javaGrowing 閱讀(322) | 評論 (0)編輯 收藏

    在Web客戶端使用xmlhttp對象,可以十分方便的和服務器交換數據,我們可以獲取和發送任何類型的數據,甚至二進制數據到服務器上。xmlhttp技術同時也是目前大多數無刷新頁面使用的和服務器交換數據的方式,這種方式比以往的隱藏iframe的方法要方便和經濟的多。

    ??? 同時讓我們高興得是xmlhttp并不是IE特有的東西,雖然目前還不是W3C的標準,不過IE, Netscape/Mozilla, 和Safari都支持。在IE中我們使用new ActiveXObject('MSXML2.XMLHTTP')或者new ActiveXObject("Microsoft.XMLHTTP")來獲得的xmlhttp對象實例,使用前者還是后者和客戶端機器安裝的MSXML版本有關。在Netscape/Mozilla和Safari中,使用new XMLHttpRequest()來獲得xmlhttp對象實例。比如在IE中,我們通常這樣使用:
    var?xmlhttp?=?null;?
    try?
    {?
    ????xmlhttp?
    =?new?ActiveXObject("MSXML2.XMLHTTP");?
    }?
    catch(e)?
    {?
    ????
    try?
    ????{?
    ????????xmlhttp?
    =?new?ActiveXObject("Microsoft.XMLHTTP");?
    ????}?
    ????
    catch(e2){}?
    }?


    ??? 使用xmlhttp對象其實是并不是什么困難的事,它一共就6個方法8個屬性。不過它最主要的是提供了兩種執行模式:同步模式和異步模式。同步模式可以比較精確的控制程序流程,可是如果服務器的Response太慢,browser會有死掉失去相應的問題;而使用異步模式由于是事件觸發方式控制流程,會給程序運行帶來一些不可與預計的問題,因為你不知道客戶端等待服務器Response的過程中,用戶會在browser里做什么操作。?

    ??? 下面是一個同步方式獲取服務器數據的簡單示例:

    function?GetRemoteData(url)
    {
    ????
    var?xmlhttp?=?new?ActiveXObject("Microsoft.XMLHTTP");
    ????
    try
    ????{??
    ?????????xmlhttp.open('GET',?url,?
    false);
    ?????????
    if?(?xmlhttp.status?==?200?)
    ?????????{
    ?????????????
    return?xmlhttp.responseText;
    ?????????}
    ?????????
    throw?'';?
    ????}
    ????
    catch(e)
    ????{
    ?????????
    return?'';
    ????}
    }


    ??? XMLHTTP對象的屬性和方法列表(來自IXMLHTTPRequest接口):

    ???
    NameTypeDescription
    onreadystatechange N/A指定當就緒狀態發生改變時調用的事件處理函數,僅用于異步操作?
    readyState Long異步操作的狀態:未初始化(0),正在加載(1),已加載(2),交互(3),已完成(4)
    responseBody Variant將響應信息正文作為unsigned byte數組返回
    responseStream Variant將響應信息正文作為一個ADO Stream對象返回
    responseText String將響應信息正文作為一個文本字符串返回
    responseXML Object通過XMLDom將響應信息正文解析為XMLDocument對象
    status Long服務器返回的HTTP狀態碼
    statusText String服務器HTTP響應行狀態
    ???
    NameDesciption
    abort取消當前 HTTP 請求
    getAllResponseHeaders從響應信息中檢索所有的標頭字段
    getResponseHeader從響應信息正文中獲得一個 HTTP 標頭值
    open(method, url, boolAsync, bstrUser, bstrPassword)打開一個與 HTTP 服務器的連接
    send(varBody)設定一個請求的標頭字段
    setRequestHeader(bstrHeader, bstrValue)向 HTTP 服務器發送請求。可包含正文。

    ??? 這里面顯然就open方法比較麻煩,帶了一大堆參數,它們的含義分別是:
    ???
    ParameterDescription
    methodHTTP的通信方式,比如GET, HEAD, POST, PUT, DELETE, CONNECT等
    url接收數據的服務器的URL地址,URL可帶QueryString
    boolAsync一個布爾標識,說明請求是否為異步的。如果是異步通信方式,客戶端就不等待服務器的響應;如果是同步方式,客戶機會等到服務器返回消息后才去執行其它操作
    bstrUser用戶ID,用于服務器身份驗證
    bstrPassword用戶密碼,用于服務器身份驗證

    ??? 異步通訊的示例:
    xmlhttp.open("GET",?"default.aspx",?true);
    xmlhttp.onreadystatechange?
    =?function()
    {
    ????
    if?(?xmlhttp.readyState==4?)
    ????{
    ????????alert(xmlhttp.responseText);
    ????}
    }
    xmlhttp.send(
    null);


    ??? 其實使用xmlhttp就這么簡單,復雜的是服務器端數據的組織方式,而且需要開發人員同時熟悉Client和Server端的開發,才能事半功倍。可是好像說了半天這個玩意兒和xml沒有什么關系啊,怎么叫xmlhttp呢?我們注意到response的數據類型中有一個responseXML,不過它解析返回的XMLDocument屬于XMLDOM的內容了,和使用xmlhttp來和服務器通訊的關系并不大,以后再來細說。

    posted @ 2006-07-29 11:46 javaGrowing 閱讀(337) | 評論 (0)編輯 收藏

    javax.servlet.jsp.JspWriter?out;
     javax.servlet.jsp.PageContext?pageContext?
    =

      javax.servlet.jsp.JspFactory.getDefaultFactory().getPageContext(
    this ,?request,?response,? null ,? true ,? 8192 ,? true );

     out?
    = ?pageContext.getOut();

    posted @ 2006-06-14 23:15 javaGrowing 閱讀(3007) | 評論 (0)編輯 收藏

    Oracle/PLSQL: To_Date Function


    In Oracle/PLSQL, the to_date function converts a string to a date.

    The syntax for the to_date function is:

    to_date( string1, [ format_mask ], [ nls_language ] )

    string1 is the string that will be converted to a date.

    format_mask is optional. This is the format that will be used to convert string1 to a date.

    nls_language is optional. This is the nls language used to convert string1 to a date.


    The following is a list of options for the format_mask parameter. These parameters can be used in many combinations.

    Parameter Explanation
    YEAR Year, spelled out
    YYYY 4-digit year
    YYY
    YY
    Y
    Last 3, 2, or 1 digit(s) of year.
    IYY
    IY
    I
    Last 3, 2, or 1 digit(s) of ISO year.
    IYYY 4-digit year based on the ISO standard
    RRRR Accepts a 2-digit year and returns a 4-digit year.
    A value between 0-49 will return a 20xx year.
    A value between 50-99 will return a 19xx year.
    Q Quarter of year (1, 2, 3, 4; JAN-MAR = 1).
    MM Month (01-12; JAN = 01).
    MON Abbreviated name of month.
    MONTH Name of month, padded with blanks to length of 9 characters.
    RM Roman numeral month (I-XII; JAN = I).
    WW Week of year (1-53) where week 1 starts on the first day of the year and continues to the seventh day of the year.
    W Week of month (1-5) where week 1 starts on the first day of the month and ends on the seventh.
    IW Week of year (1-52 or 1-53) based on the ISO standard.
    D Day of week (1-7).
    DAY Name of day.
    DD Day of month (1-31).
    DDD Day of year (1-366).
    DY Abbreviated name of day.
    J Julian day; the number of days since January 1, 4712 BC.
    HH Hour of day (1-12).
    HH12 Hour of day (1-12).
    HH24 Hour of day (0-23).
    MI Minute (0-59).
    SS Second (0-59).
    SSSSS Seconds past midnight (0-86399).
    FF Fractional seconds. Use a value from 1 to 9 after FF to indicate the number of digits in the fractional seconds. For example, 'FF4'.
    AM, A.M., PM, or P.M. Meridian indicator
    AD or A.D AD indicator
    BC or B.C. BC indicator
    TZD Daylight savings information. For example, 'PST'
    TZH Time zone hour.
    TZM Time zone minute.
    TZR Time zone region.

    For example:

    to_date('2003/07/09', 'yyyy/mm/dd') would return a date value of July 9, 2003.
    to_date('070903', 'MMDDYY') would return a date value of July 9, 2003.
    to_date('20020315', 'yyyymmdd') would return a date value of Mar 15, 2002.
    posted @ 2006-05-22 18:45 javaGrowing 閱讀(1057) | 評論 (1)編輯 收藏

    簡介:

    java.util.regex是一個用正則表達式所訂制的模式來對字符串進行匹配工作的類庫包。

    它包括兩個類: PatternMatcher

    Pattern 一個Pattern是一個正則表達式經編譯后的表現模式。
    Matcher 一個Matcher對象是一個狀態機器,它依據Pattern對象做為匹配模式對字符串展開匹配檢查。

    首先一個Pattern實例訂制了一個所用語法與PERL的類似的正則表達式經編譯后的模式,然后一個Matcher實例在這個給定的Pattern實例的模式控制下進行字符串的匹配工作。

    以下我們就分別來看看這兩個類:





    回頁首


    Pattern類:

    Pattern的方法如下:

    static Pattern compile(String regex)
    將給定的正則表達式編譯并賦予給Pattern類
    static Pattern compile(String regex, int flags)
    同上,但增加flag參數的指定,可選的flag參數包括:CASE INSENSITIVE,MULTILINE,DOTALL,UNICODE CASE, CANON EQ
    int flags()
    返回當前Pattern的匹配flag參數.
    Matcher matcher(CharSequence input)
    生成一個給定命名的Matcher對象
    static boolean matches(String regex, CharSequence input)
    編譯給定的正則表達式并且對輸入的字串以該正則表達式為模開展匹配,該方法適合于該正則表達式只會使用一次的情況,也就是只進行一次匹配工作,因為這種情況下并不需要生成一個Matcher實例。
    String pattern()
    返回該Patter對象所編譯的正則表達式。
    String[] split(CharSequence input)
    將目標字符串按照Pattern里所包含的正則表達式為模進行分割。
    String[] split(CharSequence input, int limit)
    作用同上,增加參數limit目的在于要指定分割的段數,如將limi設為2,那么目標字符串將根據正則表達式分為割為兩段。

    一個正則表達式,也就是一串有特定意義的字符,必須首先要編譯成為一個Pattern類的實例,這個Pattern對象將會使用 matcher()方法來生成一個Matcher實例,接著便可以使用該 Matcher實例以編譯的正則表達式為基礎對目標字符串進行匹配工作,多個Matcher是可以共用一個Pattern對象的。

    現在我們先來看一個簡單的例子,再通過分析它來了解怎樣生成一個Pattern對象并且編譯一個正則表達式,最后根據這個正則表達式將目標字符串進行分割:

    												
    														import java.util.regex.*;
    public class Replacement{
          public static void main(String[] args) throws Exception {
            // 生成一個Pattern,同時編譯一個正則表達式
            Pattern p = Pattern.compile("[/]+");
            //用Pattern的split()方法把字符串按"/"分割
            String[] result = p.split(
    "Kevin has seen《LEON》seveal times,because it is a good film."
    +"/ 凱文已經看過《這個殺手不太冷》幾次了,因為它是一部"
    +"好電影。/名詞:凱文。");
            for (int i=0; i<result.length; i++)
                System.out.println(result[i]);
          }
    }
    
    												
    										

    輸出結果為:

    Kevin has seen《LEON》seveal times,because it is a good film.
    凱文已經看過《這個殺手不太冷》幾次了,因為它是一部好電影。
    名詞:凱文。
    

    很明顯,該程序將字符串按"/"進行了分段,我們以下再使用 split(CharSequence input, int limit)方法來指定分段的段數,程序改動為:
    tring[] result = p.split("Kevin has seen《LEON》seveal times,because it is a good film./ 凱文已經看過《這個殺手不太冷》幾次了,因為它是一部好電影。/名詞:凱文。",2);

    這里面的參數"2"表明將目標語句分為兩段。

    輸出結果則為:

    Kevin has seen《LEON》seveal times,because it is a good film.
    凱文已經看過《這個殺手不太冷》幾次了,因為它是一部好電影。/名詞:凱文。

    由上面的例子,我們可以比較出java.util.regex包在構造Pattern對象以及編譯指定的正則表達式的實現手法與我們在上一篇中所介紹的Jakarta-ORO 包在完成同樣工作時的差別,Jakarta-ORO 包要先構造一個PatternCompiler類對象接著生成一個Pattern對象,再將正則表達式用該PatternCompiler類的compile()方法來將所需的正則表達式編譯賦予Pattern類:

    PatternCompiler orocom=new Perl5Compiler();

    Pattern pattern=orocom.compile("REGULAR EXPRESSIONS");

    PatternMatcher matcher=new Perl5Matcher();

    但是在java.util.regex包里,我們僅需生成一個Pattern類,直接使用它的compile()方法就可以達到同樣的效果: Pattern p = Pattern.compile("[/]+");

    因此似乎java.util.regex的構造法比Jakarta-ORO更為簡潔并容易理解。





    回頁首


    Matcher類:

    Matcher方法如下:

    Matcher appendReplacement(StringBuffer sb, String replacement)
    將當前匹配子串替換為指定字符串,并且將替換后的子串以及其之前到上次匹配子串之后的字符串段添加到一個StringBuffer對象里。
    StringBuffer appendTail(StringBuffer sb)
    將最后一次匹配工作后剩余的字符串添加到一個StringBuffer對象里。
    int end()
    返回當前匹配的子串的最后一個字符在原目標字符串中的索引位置 。
    int end(int group)
    返回與匹配模式里指定的組相匹配的子串最后一個字符的位置。
    boolean find()
    嘗試在目標字符串里查找下一個匹配子串。
    boolean find(int start)
    重設Matcher對象,并且嘗試在目標字符串里從指定的位置開始查找下一個匹配的子串。
    String group()
    返回當前查找而獲得的與組匹配的所有子串內容
    String group(int group)
    返回當前查找而獲得的與指定的組匹配的子串內容
    int groupCount()
    返回當前查找所獲得的匹配組的數量。
    boolean lookingAt()
    檢測目標字符串是否以匹配的子串起始。
    boolean matches()
    嘗試對整個目標字符展開匹配檢測,也就是只有整個目標字符串完全匹配時才返回真值。
    Pattern pattern()
    返回該Matcher對象的現有匹配模式,也就是對應的Pattern 對象。
    String replaceAll(String replacement)
    將目標字符串里與既有模式相匹配的子串全部替換為指定的字符串。
    String replaceFirst(String replacement)
    將目標字符串里第一個與既有模式相匹配的子串替換為指定的字符串。
    Matcher reset()
    重設該Matcher對象。
    Matcher reset(CharSequence input)
    重設該Matcher對象并且指定一個新的目標字符串。
    int start()
    返回當前查找所獲子串的開始字符在原目標字符串中的位置。
    int start(int group)
    返回當前查找所獲得的和指定組匹配的子串的第一個字符在原目標字符串中的位置。

    (光看方法的解釋是不是很不好理解?不要急,待會結合例子就比較容易明白了)

    一個Matcher實例是被用來對目標字符串進行基于既有模式(也就是一個給定的Pattern所編譯的正則表達式)進行匹配查找的,所有往Matcher的輸入都是通過CharSequence接口提供的,這樣做的目的在于可以支持對從多元化的數據源所提供的數據進行匹配工作。

    我們分別來看看各方法的使用:

    ★matches()/lookingAt ()/find():
    一個Matcher對象是由一個Pattern對象調用其matcher()方法而生成的,一旦該Matcher對象生成,它就可以進行三種不同的匹配查找操作:

    1. matches()方法嘗試對整個目標字符展開匹配檢測,也就是只有整個目標字符串完全匹配時才返回真值。
    2. lookingAt ()方法將檢測目標字符串是否以匹配的子串起始。
    3. find()方法嘗試在目標字符串里查找下一個匹配子串。

    以上三個方法都將返回一個布爾值來表明成功與否。

    ★replaceAll ()/appendReplacement()/appendTail():
    Matcher類同時提供了四個將匹配子串替換成指定字符串的方法:

    1. replaceAll()
    2. replaceFirst()
    3. appendReplacement()
    4. appendTail()

    replaceAll()與replaceFirst()的用法都比較簡單,請看上面方法的解釋。我們主要重點了解一下appendReplacement()和appendTail()方法。

    appendReplacement(StringBuffer sb, String replacement) 將當前匹配子串替換為指定字符串,并且將替換后的子串以及其之前到上次匹配子串之后的字符串段添加到一個StringBuffer對象里,而appendTail(StringBuffer sb) 方法則將最后一次匹配工作后剩余的字符串添加到一個StringBuffer對象里。

    例如,有字符串fatcatfatcatfat,假設既有正則表達式模式為"cat",第一次匹配后調用appendReplacement(sb,"dog"),那么這時StringBuffer sb的內容為fatdog,也就是fatcat中的cat被替換為dog并且與匹配子串前的內容加到sb里,而第二次匹配后調用appendReplacement(sb,"dog"),那么sb的內容就變為fatdogfatdog,如果最后再調用一次appendTail(sb),那么sb最終的內容將是fatdogfatdogfat。

    還是有點模糊?那么我們來看個簡單的程序:

    												
    														//該例將把句子里的"Kelvin"改為"Kevin"
    import java.util.regex.*;
    public class MatcherTest{
        public static void main(String[] args) 
                             throws Exception {
            //生成Pattern對象并且編譯一個簡單的正則表達式"Kelvin"
            Pattern p = Pattern.compile("Kevin");
            //用Pattern類的matcher()方法生成一個Matcher對象
            Matcher m = p.matcher("Kelvin Li and Kelvin Chan are both working in Kelvin Chen's KelvinSoftShop company");
            StringBuffer sb = new StringBuffer();
            int i=0;
            //使用find()方法查找第一個匹配的對象
            boolean result = m.find();
            //使用循環將句子里所有的kelvin找出并替換再將內容加到sb里
            while(result) {
                i++;
                m.appendReplacement(sb, "Kevin");
                System.out.println("第"+i+"次匹配后sb的內容是:"+sb);
                //繼續查找下一個匹配對象
                result = m.find();
            }
            //最后調用appendTail()方法將最后一次匹配后的剩余字符串加到sb里;
            m.appendTail(sb);
            System.out.println("調用m.appendTail(sb)后sb的最終內容是:"+ sb.toString());
        }
    }
    												
    										

    最終輸出結果為:
    第1次匹配后sb的內容是:Kevin
    第2次匹配后sb的內容是:Kevin Li and Kevin
    第3次匹配后sb的內容是:Kevin Li and Kevin Chan are both working in Kevin
    第4次匹配后sb的內容是:Kevin Li and Kevin Chan are both working in Kevin Chen's Kevin
    調用m.appendTail(sb)后sb的最終內容是:Kevin Li and Kevin Chan are both working in Kevin Chen's KevinSoftShop company.

    看了上面這個例程是否對appendReplacement(),appendTail()兩個方法的使用更清楚呢,如果還是不太肯定最好自己動手寫幾行代碼測試一下。

    ★group()/group(int group)/groupCount():
    該系列方法與我們在上篇介紹的Jakarta-ORO中的MatchResult .group()方法類似(有關Jakarta-ORO請參考上篇的內容),都是要返回與組匹配的子串內容,下面代碼將很好解釋其用法:

    												
    														import java.util.regex.*;
    
    public class GroupTest{
        public static void main(String[] args) 
                             throws Exception {
            Pattern p = Pattern.compile("(ca)(t)");        
            Matcher m = p.matcher("one cat,two cats in the yard");
            StringBuffer sb = new StringBuffer();
            boolean result = m.find();
            System.out.println("該次查找獲得匹配組的數量為:"+m.groupCount());
            for(int i=1;i<=m.groupCount();i++){
             System.out.println("第"+i+"組的子串內容為: "+m.group(i));
            }
        }
    }
    												
    										

    輸出為:
    該次查找獲得匹配組的數量為:2
    第1組的子串內容為:ca
    第2組的子串內容為:t

    Matcher對象的其他方法因比較好理解且由于篇幅有限,請讀者自己編程驗證。





    回頁首


    一個檢驗Email地址的小程序:

    最后我們來看一個檢驗Email地址的例程,該程序是用來檢驗一個輸入的EMAIL地址里所包含的字符是否合法,雖然這不是一個完整的EMAIL地址檢驗程序,它不能檢驗所有可能出現的情況,但在必要時您可以在其基礎上增加所需功能。

    												
    														import java.util.regex.*;
    public class Email {
       public static void main(String[] args) throws Exception {
          String input = args[0];
          //檢測輸入的EMAIL地址是否以 非法符號"."或"@"作為起始字符      
          Pattern p = Pattern.compile("^\\.|^\\@");
          Matcher m = p.matcher(input);
          if (m.find()){
            System.err.println("EMAIL地址不能以'.'或'@'作為起始字符");
          }
          //檢測是否以"www."為起始
          p = Pattern.compile("^www\\.");
          m = p.matcher(input);
          if (m.find()) {
            System.out.println("EMAIL地址不能以'www.'起始");
          }
          //檢測是否包含非法字符
          p = Pattern.compile("[^A-Za-z0-9\\.\\@_\\-~#]+");
          m = p.matcher(input);
          StringBuffer sb = new StringBuffer();
          boolean result = m.find();
          boolean deletedIllegalChars = false;
          while(result) {
             //如果找到了非法字符那么就設下標記
             deletedIllegalChars = true;
             //如果里面包含非法字符如冒號雙引號等,那么就把他們消去,加到SB里面
             m.appendReplacement(sb, "");
             result = m.find();
          }
          m.appendTail(sb);
          input = sb.toString();
          if (deletedIllegalChars) {
              System.out.println("輸入的EMAIL地址里包含有冒號、逗號等非法字符,請修改");
              System.out.println("您現在的輸入為: "+args[0]);
              System.out.println("修改后合法的地址應類似: "+input);
         }
       }
    }
    												
    										

    例如,我們在命令行輸入:java Email www.kevin@163.net

    那么輸出結果將會是:EMAIL地址不能以'www.'起始

    如果輸入的EMAIL為@kevin@163.net

    則輸出為:EMAIL地址不能以'.'或'@'作為起始字符

    當輸入為:cgjmail#$%@163.net

    那么輸出就是:

    輸入的EMAIL地址里包含有冒號、逗號等非法字符,請修改
    您現在的輸入為: cgjmail#$%@163.net
    修改后合法的地址應類似: cgjmail@163.net




    回頁首


    總結:

    本文介紹了jdk1.4.0-beta3里正則表達式庫--java.util.regex中的類以及其方法,如果結合與上一篇中所介紹的Jakarta-ORO API作比較,讀者會更容易掌握該API的使用,當然該庫的性能將在未來的日子里不斷擴展,希望獲得最新信息的讀者最好到及時到SUN的網站去了解。





    回頁首


    結束語:

    本來計劃再多寫一篇介紹一下需付費的正則表達式庫中較具代表性的作品,但覺得既然有了免費且優秀的正則表達式庫可以使用,何必還要去找需付費的呢,相信很多讀者也是這么想的:,所以有興趣了解更多其他的第三方正則表達式庫的朋友可以自己到網上查找或者到我在參考資料里提供的網址去看看。





    回頁首


    參考資料





    回頁首


    關于作者

    陳廣佳 Kevin Chen,汕頭大學電子信息工程系工科學士,臺灣大新出版社珠海區開發部,現正圍繞中日韓電子資料使用JAVA開發電子詞典等相關項目。可通過E-mail: cgjmail@163.net于他聯系。

    posted @ 2006-05-22 13:24 javaGrowing 閱讀(374) | 評論 (0)編輯 收藏

    僅列出標題
    共19頁: First 上一頁 6 7 8 9 10 11 12 13 14 下一頁 Last 
    主站蜘蛛池模板: 亚洲日韩一中文字暮| xxxx日本在线播放免费不卡| 在线免费观看国产视频| 一区二区三区免费在线观看| 久久精品亚洲综合一品| 最新欧洲大片免费在线| 狠狠热精品免费观看| 亚洲人成网址在线观看| 国产小视频在线免费| 鲁丝片一区二区三区免费| 亚洲色一区二区三区四区| 亚洲中文字幕无码久久综合网| 日本免费xxxx色视频| 色噜噜狠狠色综合免费视频| 亚洲黄色一级毛片| 亚洲?v无码国产在丝袜线观看| 99爱在线观看免费完整版| 精品特级一级毛片免费观看| 亚洲精品影院久久久久久| 亚洲AV无码不卡在线观看下载| 污污网站免费观看| 黄页网站在线观看免费| 亚洲成人黄色在线| 国产亚洲自拍一区| 日本二区免费一片黄2019| 亚州免费一级毛片| A级毛片高清免费视频在线播放| 亚洲国产精品无码久久| 亚洲精品影院久久久久久| 亚洲精品无码永久在线观看你懂的| 在线免费观看色片| 日本免费xxxx| 99视频在线看观免费| 国产精品福利片免费看| 蜜桃传媒一区二区亚洲AV| 亚洲婷婷天堂在线综合| 亚洲a在线视频视频| 亚洲综合伊人久久综合| 午夜亚洲国产成人不卡在线| 成人免费视频软件网站| 蜜臀AV免费一区二区三区|