javaGrowing

            BlogJava :: 首頁 :: 新隨筆 :: 聯(lián)系 :: 聚合  :: 管理 ::
            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 閱讀(318) | 評論 (0)編輯 收藏

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

          ??? 同時讓我們高興得是xmlhttp并不是IE特有的東西,雖然目前還不是W3C的標(biāo)準(zhǔn),不過IE, Netscape/Mozilla, 和Safari都支持。在IE中我們使用new ActiveXObject('MSXML2.XMLHTTP')或者new ActiveXObject("Microsoft.XMLHTTP")來獲得的xmlhttp對象實例,使用前者還是后者和客戶端機(jī)器安裝的MSXML版本有關(guān)。在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個屬性。不過它最主要的是提供了兩種執(zhí)行模式:同步模式和異步模式。同步模式可以比較精確的控制程序流程,可是如果服務(wù)器的Response太慢,browser會有死掉失去相應(yīng)的問題;而使用異步模式由于是事件觸發(fā)方式控制流程,會給程序運(yùn)行帶來一些不可與預(yù)計的問題,因為你不知道客戶端等待服務(wù)器Response的過程中,用戶會在browser里做什么操作。?

          ??? 下面是一個同步方式獲取服務(wù)器數(shù)據(jù)的簡單示例:

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

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

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


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

          posted @ 2006-07-29 11:46 javaGrowing 閱讀(331) | 評論 (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 閱讀(3001) | 評論 (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 閱讀(1050) | 評論 (1)編輯 收藏

          簡介:

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

          它包括兩個類: PatternMatcher

          Pattern 一個Pattern是一個正則表達(dá)式經(jīng)編譯后的表現(xiàn)模式。
          Matcher 一個Matcher對象是一個狀態(tài)機(jī)器,它依據(jù)Pattern對象做為匹配模式對字符串展開匹配檢查。

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

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





          回頁首


          Pattern類:

          Pattern的方法如下:

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

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

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

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

          輸出結(jié)果為:

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

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

          這里面的參數(shù)"2"表明將目標(biāo)語句分為兩段。

          輸出結(jié)果則為:

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

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

          PatternCompiler orocom=new Perl5Compiler();

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

          PatternMatcher matcher=new Perl5Matcher();

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

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





          回頁首


          Matcher類:

          Matcher方法如下:

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

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

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

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

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

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

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

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

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

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

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

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

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

          												
          														//該例將把句子里的"Kelvin"改為"Kevin"
          import java.util.regex.*;
          public class MatcherTest{
              public static void main(String[] args) 
                                   throws Exception {
                  //生成Pattern對象并且編譯一個簡單的正則表達(dá)式"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();
                  //使用循環(huán)將句子里所有的kelvin找出并替換再將內(nèi)容加到sb里
                  while(result) {
                      i++;
                      m.appendReplacement(sb, "Kevin");
                      System.out.println("第"+i+"次匹配后sb的內(nèi)容是:"+sb);
                      //繼續(xù)查找下一個匹配對象
                      result = m.find();
                  }
                  //最后調(diào)用appendTail()方法將最后一次匹配后的剩余字符串加到sb里;
                  m.appendTail(sb);
                  System.out.println("調(diào)用m.appendTail(sb)后sb的最終內(nèi)容是:"+ sb.toString());
              }
          }
          												
          										

          最終輸出結(jié)果為:
          第1次匹配后sb的內(nèi)容是:Kevin
          第2次匹配后sb的內(nèi)容是:Kevin Li and Kevin
          第3次匹配后sb的內(nèi)容是:Kevin Li and Kevin Chan are both working in Kevin
          第4次匹配后sb的內(nèi)容是:Kevin Li and Kevin Chan are both working in Kevin Chen's Kevin
          調(diào)用m.appendTail(sb)后sb的最終內(nèi)容是: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()方法類似(有關(guān)Jakarta-ORO請參考上篇的內(nèi)容),都是要返回與組匹配的子串內(nèi)容,下面代碼將很好解釋其用法:

          												
          														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("該次查找獲得匹配組的數(shù)量為:"+m.groupCount());
                  for(int i=1;i<=m.groupCount();i++){
                   System.out.println("第"+i+"組的子串內(nèi)容為: "+m.group(i));
                  }
              }
          }
          												
          										

          輸出為:
          該次查找獲得匹配組的數(shù)量為:2
          第1組的子串內(nèi)容為:ca
          第2組的子串內(nèi)容為:t

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





          回頁首


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

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

          												
          														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) {
                   //如果找到了非法字符那么就設(shè)下標(biāo)記
                   deletedIllegalChars = true;
                   //如果里面包含非法字符如冒號雙引號等,那么就把他們消去,加到SB里面
                   m.appendReplacement(sb, "");
                   result = m.find();
                }
                m.appendTail(sb);
                input = sb.toString();
                if (deletedIllegalChars) {
                    System.out.println("輸入的EMAIL地址里包含有冒號、逗號等非法字符,請修改");
                    System.out.println("您現(xiàn)在的輸入為: "+args[0]);
                    System.out.println("修改后合法的地址應(yīng)類似: "+input);
               }
             }
          }
          												
          										

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

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

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

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

          當(dāng)輸入為:cgjmail#$%@163.net

          那么輸出就是:

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




          回頁首


          總結(jié):

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





          回頁首


          結(jié)束語:

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





          回頁首


          參考資料





          回頁首


          關(guān)于作者

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

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

          僅列出標(biāo)題
          共19頁: First 上一頁 6 7 8 9 10 11 12 13 14 下一頁 Last 
          主站蜘蛛池模板: 桓仁| 岢岚县| 赤城县| 城口县| 滕州市| 双牌县| 巴青县| 石阡县| 叙永县| 南宁市| 广安市| 宜君县| 西充县| 龙门县| 霍林郭勒市| 会同县| 华池县| 雅安市| 博客| 越西县| 盐山县| 会同县| 马关县| 无为县| 揭西县| 诸暨市| 陆丰市| 西畴县| 沾益县| 武川县| 潜江市| 新龙县| 三台县| 哈密市| 桦甸市| 辽宁省| 汝南县| 新闻| 武清区| 同仁县| 中江县|