從J2SE1.4起Java增加了對正則表達式的支持就是java.util.regex包
package testreg;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* <p>Title: 正則表達式的研究</p>
* <p>Description:
* 最近在工作中常常用到一些正則表達式的使用問題,到網(wǎng)上去找介紹大多是一鱗半爪。求人不如
* 求已。一狠心,自己看!這兩天利用我們項目兩期之間的一點空閑對J2SE所支持的正則表達式來
* 了個徹底研究!代價是……就是浪廢了部門近十二張白紙。閑話少說,書歸正傳。
* 原理:
* 正則表達式的原理是有限狀態(tài)自動機,自動機內(nèi)部有有限個狀態(tài),有一個初始狀態(tài),有一個
* 結(jié)束狀態(tài)。自動機根據(jù)輸入和自身內(nèi)部的當前狀態(tài)來決定下一步于什么。呵呵,這是很久以前學
* 的東東了也記不清了,大家只作參照吧。
* Java中的正則表達式:
* 從J2SE1.4起Java增加了對正則表達式的支持就是java.util.regex包,這個包中主要有
* 3個類:Pattern,代表模式,就是正則表達式自身,Matcher,是一個有限狀態(tài)自動機,其實大多
* 數(shù)的活還是讓Pattern類于了,Matcher往往只是簡單的調(diào)用Pattern,不知道這是什么模式。這
* 兩個類寫的都很經(jīng)典,還有不少算法在內(nèi)值得有功力的人仔細研究一下。另一個是一個異常類當所
* 用正則表達式不正確時拋出,是運行時異常。
* 幾個難點:
* 1.line terminator
* line terminator 中文意終結(jié)符,是指一個或兩個字符組成的字符序列。java中的
* 所有l(wèi)ine terminator:
* A newline (line feed) character ('/n'),
* -----------換行符(0A)
* A carriage-return character followed immediately by a newline character ("/r/n"),
* -----------回車+換行(0D0A)
* A standalone carriage-return character ('/r'),
* -----------回車(0D)
* A next-line character ('/u0085'),
* ------------下一行符?(?表示我也不知道是什么,請大家明白的給我發(fā)mail
* A line-separator character ('/u2028'), or
* ------------行分隔符?
* A paragraph-separator character ('/u2029).
* ------------段落分隔符?
* If UNIX_LINES mode is activated, then the only line terminators recognized are newline characters.
* 如果使用unix模式則只有/n被認為是line terminator,也就是在使用pattern時如下:
* Pattern p=Pattern.compile("正則表達式",Pattern.UNIX_LINE);
* 或 Pattern p=Pattern.compile("(?d)正則表達式")
* "."匹配除line terminator以外的所有字符(未指定DOTALL時)
* 在指定DOTAll模式時"."匹配所有字符
* 2.Quantifiers,Greedy,Reluctant and Possessive.
* 這幾個詞不太好譯,原文是Greedy Quantifiers,Reluctant Quantifiers and Possessive
* Quantifiers憑我這點英語我只好譯作貪婪的量子,不情愿的量子和占有欲強的量子?這也太搞笑了,
* 好在我理解了他們的意思。這點等下我細說。
* 3. 對于[a-zA-Z],[a-d[h-i]],[^a-f],[b-f&&[a-z]],[b-f&&[^cd]]等形式的理解
* 對于上述,原文用range,union,negation,intersection,subtraction等來描述
* range表是范圍,union是并集,negation是取反,intersection是交集,subtraction
* 是……是減法??反正是減去一部分的意思
* range a-z 從a到z的小寫字母
* negation [^a-f]除了a-f之外所有的,全集是所有字符
* union [a-d[h-i]] a-d并h-i
* subtraction [b-f&&[^cd]] 就是b-f中除了cd以外的都是
* intersection[b-f&&[a-z]] 就是b-f與a-z中的公共部分
* 我總結(jié)了一下,其實就是方括號表示一個集合,集合中的元素用列舉法表示如[abcd],但太多
* 了怎么為?總不能把從a到z的全列舉吧?那就用a-z表示且省略了方括號,交集用&&表示,并集
* 省略,差集(對subtraction譯成差集還差不多)用交集和取反來表示。所以,以上的可表示為:
* [[a-z][A-Z]],[[a-d][h-i]],[^a-f],[[b-f]&&[a-z]],[[b-f]&&[^cd]]
* 這樣是不是和我們的習慣相符了.
* 4.各個標志的意義
* 在生成pattern時可以同時使用幾個標志來指定進行匹配時的方案。
* 用法形如:Pattern p=Pattern.compile(".*a?",Pattern.UNIX_LINES);
* 當同時指定多個標志時可以使用"|"操作符連接如:
* Pattern p=Pattern.compile(".*a?,Pattern.UNIX_LINES|Pattern.DOTALL);
* 也可以在表達式中指定如:
* Pattern p=Pattern.compile("(?d).*a?");
* Pattern p=Pattern.compile("(?d)(?s).*a?");
* 以上兩個定義和前面兩個對應等價
* 所有的標志如下:
* Constant Equivalent Embedded Flag Expression
Pattern.CANON_EQ None Enables canonical equivalence
Pattern.CASE_INSENSITIVE (?i) Enables case-insensitive matching
Pattern.COMMENTS (?x) Permits whitespace and comments in pattern.
Pattern.MULTILINE (?m) Enables multiline mode.
Pattern.DOATALL (?s) Enables dotall mode
Pattern.UNICODE_CASE (?u) Enables Unicode-aware case folding.
Pattern.UNIX_LINES (?d) Enables Unix lines mode
CANON_EQ 指定使用規(guī)范等價模式?這個我理解的也有限,是不是說只要指定了這個模式則
ascii碼的'a'就可以和unicode的'a'還有XXX碼的'a'相等?請教各位。(mail to me)
CASE_INSENSITIVE 指定使用大小寫不敏感的匹配模式,這個好理解,但要注意這個標志只是
對ascii碼有效,要使unicode在比較時也忽略大小寫要同時指定UNICODE_CASE,就是要指定
CASE_INSENSITIVE|UNICODE_CASE或使用(?i)(?u)
COMMENTS 指定使用注釋和忽略空白,也就是".*a"==". *a #this is comments"我想這個
* 在正則表達式很大,而且是在文件中輸入時比較有用,平時我看也用不上。
*
* MULTILINE In multiline mode the expressions ^ and $ match just after
* or just before, respectively, a line terminator or the end of the
* input sequence. By default these expressions only match at the beginning
* and the end of the entire input sequence
* 指定使用多行匹配模式,在默認模式下,^和$分別只匹配一個輸入的開始和結(jié)束。
* 在這種模式下,^和$ 除了匹配整個輸入的開始和結(jié)束外還匹配一個line terminator的后邊和
* 前邊(不是前邊和后邊,就是說^匹配line terminator的后邊$匹配line terminator的前邊。
*
* DOATALL 如指定了這個模式則"."可匹配任何字符包括line terminator
*
* UNIX_LINES 指定這個模式時只有/n被認為是line terminator而/r和/r/n都不是
*
* 其他的我一時想不起來了,在具體介紹時再說吧。
* </p>
*/
public class TestReg2
{
public static void main(String[] args)
{
String str1 = "";
Object str = "";
//注意:/r,/n,/b等轉(zhuǎn)義字符在java字符串常量中要寫成//r,//n,//b等,否則編譯都過不去
///s匹配/r,/n,/r和空格
System.out.println("//s匹配//r,//n,//r和空格 "+" /t/n/r".matches("//s{4}"));
///S和/s互逆
System.out.println("//S和//s互逆 "+"/".matches("//S"));
//.不匹配/r和/n
System.out.println(".不匹配//r和//n "+"/r".matches("."));
System.out.println("/n".matches("."));
///w匹配字母,數(shù)字和下劃線
System.out.println("//w匹配字母,數(shù)字和下劃線 "+"a8_".matches("//w//w//w"));
///W和/w互逆
System.out.println("//W和//w互逆 "+"&_".matches("//W//w"));
///d匹配數(shù)字
System.out.println("//d匹配數(shù)字 "+"8".matches("//d"));
///D與/d互逆
System.out.println("//D與//d互逆"+"%".matches("//D"));
//兩者都匹配但意文不同
System.out.println("======================");
System.out.println("表示//000a匹配//000a "+"/n".matches("/n"));
System.out.println("表示//n匹配換行 "+"/n".matches("//n"));
System.out.println("======================");
//兩者都匹配但意文不同
System.out.println("/r".matches("/r"));
System.out.println("/r".matches("//r"));
System.out.println("======================");
//^匹配開頭
System.out.println("^匹配開頭"+"hell".matches("^hell"));
System.out.println("abc/nhell".matches("^hell"));
//$匹配結(jié)束
System.out.println("$匹配結(jié)束"+"my car/nabc".matches(".*ar$"));
System.out.println("my car".matches(".*ar$"));
///b匹配界
System.out.println("//b匹配界 "+"bomb".matches("//bbom."));
System.out.println("bomb".matches(".*mb//b"));
///B與/b互逆
System.out.println("//B與//b互逆"+"abc".matches("//Babc"));
//[a-z]匹配a到z的小寫字母
System.out.println("[a-z]匹配a到z的小寫字母"+"s".matches("[a-z]"));
System.out.println("S".matches("[A-Z]"));
System.out.println("9".matches("[0-9]"));
//取反
System.out.println("取反"+"s".matches("[^a-z]"));
System.out.println("S".matches("[^A-Z]"));
System.out.println("9".matches("[^0-9]"));
//括號的作用
System.out.println("括號的作用"+"aB9".matches("[a-z][A-Z][0-9]"));
System.out.println("aB9bC6".matches("([a-z][A-Z][0-9])+"));
//或運算
System.out.println("或運算"+"two".matches("two|to|2"));
System.out.println("to".matches("two|to|2"));
System.out.println("2".matches("two|to|2"));
//[a-zA-z]==[a-z]|[A-Z]
System.out.println("[a-zA-z]==[a-z]|[A-Z]"+"a".matches("[a-zA-Z]"));
System.out.println("A".matches("[a-zA-Z]"));
System.out.println("a".matches("[a-z]|[A-Z]"));
System.out.println("A".matches("[a-z]|[A-Z]"));
//體會一下以下四個
System.out.println("體會一下以下四個/n==========================");
System.out.println(")".matches("[a-zA-Z)]"));
System.out.println(")".matches("[a-zA-Z)_-]"));
System.out.println("_".matches("[a-zA-Z)_-]"));
System.out.println("-".matches("[a-zA-Z)_-]"));
System.out.println("==========================");
System.out.println("b".matches("[abc]"));
//[a-d[f-h]]==[a-df-h]
System.out.println("[a-d[f-h]]==[a-df-h]"+"h".matches("[a-d[f-h]]"));
System.out.println("a".matches("[a-z&&[def]]"));
//取交集
System.out.println("取交集"+"a".matches("[a-z&&[def]]"));
System.out.println("b".matches("[[a-z]&&[e]]"));
//取并
System.out.println("取并"+"9".matches("[[a-c][0-9]]"));
//[a-z&&[^bc]]==[ad-z]
System.out.println("[a-z&&[^bc]]==[ad-z]"+"b".matches("[a-z&&[^bc]]"));
System.out.println("d".matches("[a-z&&[^bc]]"));
//[a-z&&[^m-p]]==[a-lq-z]
System.out.println("[a-z&&[^m-p]]==[a-lq-z]"+"d".matches("[a-z&&[^m-p]]"));
System.out.println("a".matches("//p{Lower}"));
///注意以下體會/b的用法(注意,在字符串常量中十目直接寫/b表退格,所以要寫//b
System.out.println("*********************************");
System.out.println("aawordaa".matches(".*//bword//b.*"));
System.out.println("a word a".matches(".*//bword//b.*"));
System.out.println("aawordaa".matches(".*//Bword//B.*"));
System.out.println("a word a".matches(".*//Bword//B.*"));
System.out.println("a word a".matches(".*word.*"));
System.out.println("aawordaa".matches(".*word.*"));
//體會一下組的用法
//組的順序,只數(shù)"("第一個為第一組第二個是第二組……
//第0組表示整個表達式
System.out.println("**************test group**************");
Pattern p = Pattern.compile("(([abc]+)([123]+))([-_%]+)");
Matcher m = p.matcher("aac212-%%");
System.out.println(m.matches());
m = p.matcher("cccc2223%_%_-");
System.out.println(m.matches());
System.out.println("======test group======");
System.out.println(m.group());
System.out.println(m.group(0));
System.out.println(m.group(1));
System.out.println(m.group(2));
System.out.println(m.group(3));
System.out.println(m.group(4));
System.out.println(m.groupCount());
System.out.println("========test end()=========");
System.out.println(m.end());
System.out.println(m.end(2));
System.out.println("==========test start()==========");
System.out.println(m.start());
System.out.println(m.start(2));
//test backslash測試反向引用?
Pattern pp1=Pattern.compile("(//d)//1");//這個表達式表示必須有兩相同的數(shù)字出現(xiàn)
///1表示引用第一個組/n表示引用第n個組(必須用//1而不能用/1因/1在字符串中另有意義(我也知道是什么)
Matcher mm1=pp1.matcher("3345");//33匹配但45不匹配
System.out.println("test backslash測試反向引用");
System.out.println(mm1.find());
System.out.println(mm1.find());
//體會以下不同
System.out.println("==============test find()=========");
System.out.println(m.find());
System.out.println(m.find(2));
System.out.println("這是從第三個字符(index=2)開始找的group結(jié)果");
System.out.println(m.group());
System.out.println(m.group(0));
System.out.println(m.group(1));
System.out.println(m.group(2));
System.out.println(m.group(3));
m.reset();
System.out.println(m.find());
//測試一個模式可多次匹配一個串
System.out.println("測試一個模式可多次匹配一個串");
Pattern p1 = Pattern.compile("a{2}");
Matcher m1 = p1.matcher("aaaaaa");
//這說明Matcher的matchs()方法是對事個字符串的匹配,
System.out.println(m1.matches());
System.out.println(m1.find());
System.out.println(m1.find());
System.out.println(m1.find());
System.out.println(m1.find());
//再測試matchs()
System.out.println("再測試matchs()");
Pattern p2 = Pattern.compile("(a{2})*");
Matcher m2 = p2.matcher("aaaa");
System.out.println(m2.matches());
System.out.println(m2.matches());
System.out.println(m2.matches());
//所以find是在一個串中找有沒有對應的模式,而matchs是完全匹配
//test lookupat()
System.out.println("test lookupat()");
Pattern p3 = Pattern.compile("a{2}");
Matcher m3 = p3.matcher("aaaa");
System.out.println(p3.flags());
System.out.println(m3.lookingAt());
System.out.println(m3.lookingAt());
System.out.println(m3.lookingAt());
//總結(jié)以上matchs()是整個匹配且總是從頭開始,find是部分匹配且從上一次匹配結(jié)束時開始找
//lookingAt也是從頭開始,但是部分匹配
System.out.println("======test 空白行========");
System.out.println(" /n".matches("^[ //t]*$//n"));
//演示appendXXX的用法
System.out.println("=================test append====================");
Pattern p4 = Pattern.compile("cat");
Matcher m4 = p4.matcher("one cat two cats in the yard");
StringBuffer sb = new StringBuffer();
boolean result = m4.find();
int i=0;
System.out.println("one cat two cats in the yard");
while(result)
{m4.appendReplacement(sb, "dog");
System.out.println(m4.group());
System.out.println("第"+i+++"次:"+sb.toString());
result = m4.find();
}
System.out.println(sb.toString());
m4.appendTail(sb);
System.out.println(sb.toString());
//test UNIX_LINES
System.out.println("test UNIX_LINES");
Pattern p5=Pattern.compile(".",Pattern.UNIX_LINES);
Matcher m5=p5.matcher("/n/r");
System.out.println(m5.find());
System.out.println(m5.find());
//test UNIX_LINES
System.out.println("test UNIX_LINES");
Pattern p6=Pattern.compile("(?d).");
Matcher m6=p6.matcher("/n/r");
System.out.println(m6.find());
System.out.println(m6.find());
//test UNIX_LINES
System.out.println("test UNIX_LINES");
Pattern p7=Pattern.compile(".");
Matcher m7=p7.matcher("/n/r");
System.out.println(m7.find());
System.out.println(m7.find());
//test CASE_INSENSITIVE
System.out.println("test CASE_INSENSITIVE");
Pattern p8=Pattern.compile("a",Pattern.CASE_INSENSITIVE);
Matcher m8=p8.matcher("aA");
System.out.println(m8.find());
System.out.println(m8.find());
System.out.println("test CASE_INSENSITIVE");
Pattern p9=Pattern.compile("(?i)a");
Matcher m9=p9.matcher("aA");
System.out.println(m9.find());
System.out.println(m9.find());
System.out.println("test CASE_INSENSITIVE");
Pattern p10=Pattern.compile("a");
Matcher m10=p10.matcher("aA");
System.out.println(m10.find());
System.out.println(m10.find());
//test COMMENTS
System.out.println("test COMMENTS");
Pattern p11=Pattern.compile(" a a #ccc",Pattern.COMMENTS);
Matcher m11=p11.matcher("aa a a #ccc");
System.out.println(m11.find());
System.out.println(m11.find());
System.out.println("test COMMENTS");
Pattern p12 = Pattern.compile("(?x) a a #ccc");
Matcher m12 = p12.matcher("aa a a #ccc");
System.out.println(m12.find());
System.out.println(m12.find());
//test MULTILINE這個大家多試試參照我上面對多行模式的理解
System.out.println("test MULTILINE");
Pattern p13=Pattern.compile("^.?",Pattern.MULTILINE|Pattern.DOTALL);
Matcher m13=p13.matcher("helloohelloo,loveroo");
System.out.println(m13.find());
System.out.println("start:"+m13.start()+"end:"+m13.end());
System.out.println(m13.find());
//System.out.println("start:"+m13.start()+"end:"+m13.end());
System.out.println("test MULTILINE");
Pattern p14=Pattern.compile("(?m)^hell.*oo$",Pattern.DOTALL);
Matcher m14=p14.matcher("hello,Worldoo/nhello,loveroo");
System.out.println(m14.find());
System.out.println("start:"+m14.start()+"end:"+m14.end());
System.out.println(m14.find());
//System.out.println("start:"+m14.start()+"end:"+m14.end());
System.out.println("test MULTILINE");
Pattern p15=Pattern.compile("^hell(.|[^.])*oo$");
Matcher m15=p15.matcher("hello,Worldoo/nhello,loveroo");
System.out.println(m15.find());
System.out.println("start:"+m15.start()+"end:"+m15.end());
System.out.println(m15.find());
// System.out.println("start:"+m15.start()+"end:"+m15.end());
//test DOTALL
System.out.println("test DOTALL");
Pattern p16=Pattern.compile(".",Pattern.DOTALL);
Matcher m16=p16.matcher("/n/r");
System.out.println(m16.find());
System.out.println(m16.find());
System.out.println("test DOTALL");
Pattern p17=Pattern.compile(".");
Matcher m17=p17.matcher("/n/r");
System.out.println(m17.find());
System.out.println(m17.find());
System.out.println("test DOTALL");
Pattern p18=Pattern.compile("(?s).");
Matcher m18=p18.matcher("/n/r");
System.out.println(m18.find());
System.out.println(m18.find());
//test CANON_EQ這個是jdk的例子但我實在不明白是什么意思,向大家請教
System.out.println("test CANON_EQ");
Pattern p19=Pattern.compile("a/u030A",Pattern.CANON_EQ);
System.out.println(Character.getType('/u030A'));
System.out.println("is"+Character.isISOControl('/u030A'));
System.out.println("is"+Character.isUnicodeIdentifierPart('/u030A'));
System.out.println(Character.getType('/u00E5'));
System.out.println("is"+Character.isISOControl('/u00E5'));
Matcher m19=p19.matcher("/u00E5");
System.out.println(m19.matches());
System.out.println(Character.getType('/u0085'));
System.out.println("is"+Character.isISOControl('/u0085'));
//注意下面三個例子體會Greedy,Reluctant and Possessive Quantifiers的不同
Pattern ppp=Pattern.compile(".*foo");
Matcher mmm=ppp.matcher("xfooxxxxxxfoo");
/**
* Greedy quantifiers
X? X, once or not at all
X* X, zero or more times
X+ X, one or more times
X{n} X, exactly n times
X(n,} X, at least n times
X{n,m} X, at least n but not more than m times
Greedy quantifiers是最常用的一種,如上,它的匹配方式是先匹配盡可能多的字符,當
這樣造成整個表達式整體不能匹配時就退一個字符再試比如:
.*foo與xfooxxxxxxfoo的匹配過程,.*先與整個輸入匹配,發(fā)現(xiàn)這樣不行,整個串不能匹配
* 于是退最后一個字符"o"再試,還不行,再退直到把foo都退出才發(fā)現(xiàn)匹配于是結(jié)束。因為這個過程
* 總是先從最大匹配開始到找到一個匹配,所以.*與之匹配的總是一個最大的,這個特點和資本家相似
* 故名貪婪的
*/
boolean isEnd=false;
int k=0;
System.out.println("==========");
System.out.println("xfooxxxxxxfoo");
while(isEnd==false)
try{
System.out.println("the:"+k++);
System.out.println(mmm.find());
System.out.println(mmm.end());
}catch(Exception e){
isEnd=true;
}
isEnd=false;
Pattern ppp1=Pattern.compile(".*?foo");
Matcher mmm1=ppp1.matcher("xfooxxxxxxfoo");
/**
* Reluctant quantifiers
X?? X, once or not at all
X*? X, zero or more times
X+? X, one or more times
X{n}? X, exactly n times
X(n,}? X, at least n times
X{n,m}? X, at least n but not more than m times
Reluctant quantifiers的匹配方式正好相反,它總是先從最小匹配開始,如果這時導致
整個串匹配失敗則再吃進一個字符再試,如:
.*?foo與xfooxxxxxxfoo的匹配過程,首先,.*與空串匹配,這時整個串匹配失敗,于是
* 再吃一個x,這時發(fā)現(xiàn)整個串匹配成功,當再調(diào)用find時從上次匹配結(jié)束時開始找,先吃一個
* 空串,不行,再吃一個x,不行,……直到把中間所有x都吃掉才發(fā)現(xiàn)匹配成功。這種方式總
* 是從最小匹配開始所以它能找到最多次數(shù)的匹配,但第一匹配都是最小的。它的行為有點象雇傭
* 工人,總是盡可能少的于活,故名勉強的。
*/
k=0;
System.out.println("?????????????????????");
System.out.println("xfooxxxxxxfoo");
while(isEnd==false)
try{
System.out.println("the:"+k++);
System.out.println(mmm1.find());
System.out.println(mmm1.end());
}catch(Exception e){
isEnd=true;
}
isEnd=false;
Pattern pp2=Pattern.compile(".*+foo");
Matcher mm2=pp2.matcher("xfooxxxxxxfoo");
/**
*
Possessive quantifiers
X?+ X, once or not at all
X*+ X, zero or more times
X++ X, one or more times
X{n}+ X, exactly n times
X(n,}+ X, at least n times
X{n,m}+ X, at least n but not more than m times
Possessive quantifiers 這種匹配方式與Greedy方式相似,所不同的是它不夠聰明,當
它一口吃掉所有可以吃的字符時發(fā)現(xiàn)不匹配則認為整個串都不匹配,它不會試著吐出幾個。它的行
為和大地主相似,貪婪但是愚蠢,所以名曰強占的。
*/
int ii=0;
System.out.println("+++++++++++++++++++++++++++");
System.out.println("xfooxxxxxxfoo");
while(isEnd==false)
try{
System.out.println("the:"+ii++);
System.out.println(mm2.find());
System.out.println(mm2.end());
}catch(Exception e){
isEnd=true;
}
}
}