/*******************************************************************
*7.1.1 使用RegExp對象
******************************************************************/
document.write("<br/>7.1.1 使用RegExp對象<br/>");
var sToMatch = "cat";
var reCat = /cat/;
document.writeln(reCat.test(sToMatch) + "<br/>"); // output "true"
var sToMatch2 = "a bat, a Cat, a fAt baT, a faT cat";
var reAt = /at/;
var arrMatches = reAt.exec(sToMatch2);
document.writeln(arrMatches.length + "<br/>"); // output 1
var reAt2 = /at/gi;
arrMatches = sToMatch2.match(reAt2);
document.writeln(arrMatches + "<br/>");
document.writeln(sToMatch2.search(reAt2)+ "<br/>"); //output 3
/*******************************************************************
*7.1.2 擴充的字元串方法
******************************************************************/
document.write("<br/>7.1.2 擴充的字元串方法<br/>");
var sToChange = "The sky is red.";
document.writeln(sToChange.replace("red","blue")+ "<br/>"); //output "The sky is blue."
var reRed = /red/g;
document.writeln(sToChange.replace(reRed,"blue")+ "<br/>"); //output "The sky is blue."
var sResultText = sToChange.replace(reRed, function(sMatch){
return "blue";
});
document.writeln(sResultText+ "<br/>"); //output "The sky is blue."
var sColor = "red,blue,yello,green";
var reComma = /\,/;
var arrColors = sColor.split(reComma);
document.writeln(arrColors.length+ "<br/>"); //output 4
/*******************************************************************
*7.2 簡單模式
*7.2.1 元字元
*() [] {} \ ^ $ ? * + . |
******************************************************************/
document.write("<br>7.2 簡單模式");
document.write("<br>7.2.1 元字元<br/>");
var reQMark = /\?/;
/*******************************************************************
*7.2.2 使用特殊字元
*\t 制表符
*\n 換行符
*\r 回車符
*\a 換頁符
*\e escape字元
*\cX 與X相對應的控制字元
*\b 回退字元
*\v 垂直制表符
*\0 空字元
******************************************************************/
document.write("<br>7.2.2 使用特殊字元<br/>");
var sColor = "blue";
var reB = /\x62/;//等價于 8進制/\142/,unicode/\u0062/
document.writeln(reB.test(sColor) + "<br/>"); // output "true"
//删除換行符
var reWithLines = /\n/g;
/*******************************************************************
*7.2.3 字元類
******************************************************************/
document.write("<br/>7.2.3 字元類<br/>");
//1.簡單類
var sToMatch = "a bat, a Cat, a fAt baT, a faT cat";
var reBatCatRat = /[bcf]at/gi;
//var reBatCatRat = /[\u0062cf]at/gi;
var arrMatches = sToMatch.match(reBatCatRat);
document.writeln(arrMatches.length + "<br/>"); //output "6"
//2.負向類
var sToMatch = "a bat, a Cat, a fAt baT, a faT cat";
var reBatCatRat = /[^bc]at/gi;
var arrMatches = sToMatch.match(reBatCatRat);
document.writeln(arrMatches.length + "<br/>"); //output "2"
//3.範圍類
var sToMatch = "num1, num2, num3, num4, num5, num6, num7, num8, num9";
var reOneToFour = /num[1-4]/gi;
var reNotOneToFour = /num[^1-4]/gi;
var arrMatches = sToMatch.match(reOneToFour);
document.writeln(arrMatches.length + "<br/>"); //output "4"
document.writeln(sToMatch.match(reNotOneToFour).length + "<br/>"); //output "5"
//4.組合類
//[a-m1-4\n]
//5.預定義類
/**
* . [^\n\r] 除了換行和回車之外的任意字元
* \d [0-9] 數字
* \D [^0-9] 非數字字元
* \s [ \t\n\x0B\f\r] 空白字元
* \S [^ \t\n\x0B\f\r]非空白字元
* \w [a-zA-Z_0-9] 單詞字元(所有的字母、所有的數字和下劃線)
* \W [^a-zA-Z_0-9] 非單詞字元
*/
var sToMatch = "567 9838 abc";
var reThreeNums = /\d{3} \d{4}/;
document.writeln(reThreeNums.test(sToMatch) + "<br/>"); //output "true"
/*******************************************************************
*7.2.4 量詞
* ? times = 0, 1
* * (星号) times = 0, 1, 2, ...
* + times = 1, 2, ...
* {n} times = n
* {n,m} times = n, n+1, ..., m-1, m
* {n,} itmes = n, n+1, ...
******************************************************************/
document.write("<br/>7.2.4 量詞<br/>");
//1.簡單量詞
var reBreadReadOrRed = /b?red?d/; //比對bread, read, red
//2.貪婪的、惰性的和支配性的量詞
/**
* 貪婪量詞:先看整個字元串是否比對,如果沒有,就去掉最後一個,一直到發現一個比對或是不剩任何字元
* 惰性量詞:從一個字元串開始讀入,如果沒有,就加入第二個字元,如此知道發現比對或整個字元串都檢查過也沒有比對
* 支配量詞:隻嘗試比對整個字元串 -> 目前大多浏覽器不支援
*******************************************************************
* 貪婪 惰性 支配
* ? ?? ?+
* * *? *+
* + +? ++
* {n} {n}? {n}+
* {n,m} {n,m}? {n,m}+
* {n,} {n,}? {n,}+
*******************************************************************
*/
var sToMatch = "abbbaabbbaaabbb1234";
var re1 = /.*bbb/g;
var re2 = /.*?bbb/g;
//var re3 = /.*+bbb/g;
document.writeln(sToMatch.match(re1) + "<br/>"); //output "abbbaabbbaaabbb"
document.writeln(sToMatch.match(re2) + "<br/>"); //output "abbb,aabbb,aaabbb"
//document.writeln(sToMatch.match(re3) + "<br/>"); //output "abbbaabbbaaabbb"
/*******************************************************************
*7.4 了解RegExp對象
*7.4.1 執行個體屬性
* global - Boolean
* ignoreCase - Boolean
* lastIndex - 代表下次比對将會從哪個字元位置開始(隻有當使用exec及
* test函數才會填入,否則為0)
* multiline - Boolean, 表示m是否已設定
* source - 在正規表達式的源字元串形式
******************************************************************/
document.write("<br>7.4 了解RegExp對象");
document.write("<br>7.4.1 執行個體屬性<br/>");
var reDogDog = /dogdog/g;
var reDogDog = /(dog){2}/g;
var re1 = /(dog)?/;
var re2 = /(dog)*/;
var re3 = /(dog)+/;
var re = /([bd]ad?)*/;
var re = /(mom (and dad)?)/;
//執行個體:實作js的trim()方法
String.prototype.trim = function(){
var reExtraSpace = /^\s+(.*?)\s+$/;
return this.replace(reExtraSpace,"$1");
}
document.write(" abc ".trim().length);//output 3
/*******************************************************************
*7.3.2 反向引用
*将表達式計算完後,每個分組都被存放在一個特殊的地方以備将來使用,這些存儲
*在分組中的特殊值,我們稱之為反向引用
*
*反向引用是按照從左到右遇到的左括号字元的順序進行建立和編号的
*(A?(B?(C?))) ->
* (A?(B?(C?)))
* (B?(C?))
* (C?)
******************************************************************/
document.write("<br/>7.3.2 反向引用<br/>");
//1.使用正規表達式對象的test()、match()、search()方法後,反向引用的值可
//以從RegExp構造函數中獲得
var sToMatch = "#123456789";
var reNumbers = /#(\d+)/;
reNumbers.test(sToMatch);
document.write(RegExp.$1 +"<br/>"); //output 123456789
//2.使用轉義序列
/**
* 轉義序列: /(dog)\1/ <=> /dogdog/
*/
//3.反向引用可以用在String對象的replace()方法中,這通過使用特殊序列$1、$2
//等等來實作,最佳例子是替換字元串中兩個單詞的位置
var sToChange = "1234 5678";
var reMatch = /(\d{4}) (\d{4})/;
var sNew = sToChange.replace(reMatch, "$2 $1");
document.write(sNew +"<br/>"); // output "5678 1234"
/*******************************************************************
*7.3.3 候選
******************************************************************/
document.write("<br/>7.3.3 候選<br/>");
var reBadWords = /badword|anotherbadword/gi;
var sUserInput = 'This is a string using badword1 and badword2';
var sFinalText = sUserInput.replace(reBadWords, '****');
document.write(sFinalText +"<br/>"); // output "This is a string using ****1 and ****2"
var sFinalText = sUserInput.replace(reBadWords, function(sMatch){
return sMatch.replace(/./g,"*");
});
document.write(sFinalText +"<br/>"); // output "This is a string using *******1 and *******2"
/*******************************************************************
*7.3.4 非捕獲性數組
*在較長的正規表達式中,存儲反向引用會降低比對速度;
*非捕獲性分組,仍然可以擁有與比對字元串序列同樣的能力,而無需存儲結果的開銷
*在分組的左括号後面添加?:
******************************************************************/
document.write("<br/>7.3.4 非捕獲性數組<br/>");
var sToMatch = "#123456789";
var reNumbers = /#(?:\d+)/;
reNumbers.test(sToMatch);
document.write("nothing:" + RegExp.$1 +"<br/>"); // output ""
//執行個體:去掉文本中的html标簽
String.prototype.stripHTML = function(){
return this.replace(/<(?:.|\s)*?>/, "");
}
var sTest = "<b>This would be bold</b>";
document.write(sTest.stripHTML() +"<br/>"); // output ""
/*******************************************************************
*7.3.5 前瞻
******************************************************************/
document.write("<br/>7.3.5 前瞻<br/>");
var sToMatch1 = "bedroom";
var sToMatch2 = "bedding";
var reBed = /(bed(?=room))/;
var reNotRoom = /(bed(?!room))/;
document.write(reBed.test(sToMatch1) +"<br/>"); // output "true"
document.write(RegExp.$1 +"<br/>"); // output "bed"
document.write(reBed.test(sToMatch2) +"<br/>"); // output "false"
document.write(reNotRoom.test(sToMatch1) +"<br/>"); // output "false"
document.write(RegExp.$1 +"<br/>"); // output "bed"
document.write(reNotRoom.test(sToMatch2) +"<br/>"); // output "true"
/*******************************************************************
*7.3.6 邊界
* ^ 行開頭
* $ 行結尾
* \b 單詞的邊界
* \B 非單詞的邊界
******************************************************************/
document.write("<br/>7.3.6 邊界<br/>");
var sToMatch = "Important word is the last one.";
var reLastWord = /(\w+)\.$/;
reLastWord.test(sToMatch);
document.write(RegExp.$1 +"<br/>"); // output "one"
var reFirstWord = /^(.+?)\b/;
reFirstWord.test(sToMatch);
document.write(RegExp.$1 +"<br/>"); // output "Important"
//字元串中抽取單詞
var sToMatch = "First second third fourth fifth sixth";
var reWords = /\b(\S+?)\b/g;//複雜寫法
var reWords = /(\w+)/g; //簡單寫法
var arrWords = sToMatch.match(reWords);
document.write(arrWords +"<br/>"); // output "First,second,third,fourth,fifth,sixth"
/*******************************************************************
*7.3.7 多行模式
******************************************************************/
document.write("<br/>7.3.7 多行模式<br/>");
var sToMatch = "First second\nthird fourth\nfifth sixth";
var reLastWordOnline = /(\w+)$/g;
var arrWords = sToMatch.match(reLastWordOnline);
document.write(arrWords +"<br/>"); // output "sixth"
var reLastWordOnline = /(\w+)$/gm; //多行模式
var arrWords = sToMatch.match(reLastWordOnline);
document.write(arrWords +"<br/>"); // output "second,fourth,sixth"
/*******************************************************************
*7.4 了解RegExp對象
*7.4.1 執行個體屬性
* global - Boolean
* ignoreCase - Boolean
* lastIndex - 代表下次比對将會從哪個字元位置開始(隻有當使用exec及
* test函數才會填入,否則為0)
* multiline - Boolean, 表示m是否已設定
* source - 在正規表達式的源字元串形式
******************************************************************/
document.write("<br>7.4 了解RegExp對象");
document.write("<br>7.4.1 執行個體屬性<br/>");
var reTest = /[ba]*/i;
document.write(reTest.global+"<br/>"); // output "false"
document.write(reTest.ignoreCase+"<br/>"); // output "true"
document.write(reTest.multiline+"<br/>"); // output "false"
document.write(reTest.source+"<br/>"); // output "[ba]*
var sToMatch = "bbq is short for barbecue";
var reB = /b/g;
reB.exec(sToMatch);
document.write(reB.lastIndex + "<br/>"); // output "1"
reB.exec(sToMatch);
document.write(reB.lastIndex + "<br/>"); // output "2"
reB.exec(sToMatch);
document.write(reB.lastIndex + "<br/>"); // output "18"
reB.exec(sToMatch);
document.write(reB.lastIndex + "<br/>"); // output "21"
/*******************************************************************
*7.4.2 靜态屬性
* input $_ 最後用于比對的字元串(傳遞給exec()或test()的字元串)
* lastMatch $& 最後比對的字元
* lastParen $+ 最後比對的分組
* leftContext $` 在上次比對的前面的子串
* multiline $* 用于指定是否所有的表達式都使用多行模式的布爾值
* rightContext $' 在上次比對之後的子串
******************************************************************/
document.write("<br/>7.4.2 靜态屬性<br/>");
//剛使用exec和test完成的比對的一些特定資訊
var sToMatch = "this has been a short, short summer";
var reShort = /(s)hort/g;
reShort.test(sToMatch);
document.write(RegExp.input + "<br/>"); // output "this has been a short, short summer"
document.write(RegExp.leftContext + "<br/>"); // output "this has been a "
document.write(RegExp.rightContext + "<br/>"); // output ", short summer"
document.write(RegExp.lastMatch + "<br/>"); // output "short"
document.write(RegExp.lastParen + "<br/>"); // output "s"
//每次執行exec和test時,出multiline外,所有的屬性都會被重新設定,但ie和opera
//并不支援RegExp.multiline,是以最好對每個表達式設定m值
/*******************************************************************
*7.5 常用模式
** 常見應用場景 **
* 日期
* 信用卡号
* URL
* E-mail位址
******************************************************************/
document.write("<br>7.5 常用模式<br>");
//日期格式: dd/mm/yyyy 如:31/05/2011
var reDate = /\d{1,2}\/\d{1,2}\/d{4}/; //基本比對,但沒有考慮月份及天數的有效範圍
//改進版
var reDay = /0[1-9]|[12][0-9]|3[01]/;
var reMonth = /0[1-9]|1[0-2]/;
var reYear = /19|20\d{2}/;
function isValidateDate(sText){
var reDate = /(0?[1-9]|[12][0-9]|3[01])\/(0?[1-9]|1[0-2])\/(19|20\d{2})/;
return reDate.test(sText);
}
document.write(isValidateDate("28/02/2011") + "<br/>"); // output "s"
//驗證電子郵件位址
var reEmail = /^(?:\w+.?)*\w+@(?:\w+\.?)*\w+$/;
function isValidaEmail(sText){
var reEmail = /^(?:\w+.?)*\w+@(?:\w+\.?)*\w+$/;
return reEmail.test(sText);
}
document.write(isValidaEmail("[email protected]") + "<br />");//output "true"