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 阅读(308) | 评论 (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 阅读(322) | 评论 (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 阅读(2985) | 评论 (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 阅读(1041) | 评论 (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 阅读(363) | 评论 (0)编辑 收藏

仅列出标题
共19页: First 上一页 6 7 8 9 10 11 12 13 14 下一页 Last