1. regular expression object宣告方式(有兩種方式)
var re = new RegExp(pattern,flag); //method 1 var re = /pattern/flag //method 2根據W3School所描述的flag代表比對的方式
| i | 忽略大小寫的比對方是 |
| g | 全域比對的方式(即會把內容符合的都比對,此方法會搭配exec()這個function使用) |
| m | 執行多行比對 |
2. 比對的特殊符號
這個部分必須說有點討厭,符號之多,要記起來不是那麼容易,需要花點力氣在這部分!符號主要分成4個部分| Brackets(中括號) | Metacharacters(特殊符號) | Quantifiers(量詞) | 其他特殊字元 |
Brackets
| [abc] | 找出符合括號內的字元,本例為找出符合a or b or c |
| [^abc] | 找出不在括號內的字元 |
| [0-9] | 找出任何從0~9的數字 |
| [a-z] | 找出任何從a~z的小寫字母 |
| [A-Z] | 找出任何從A~Z的大寫字母 |
| [A-z] | 找出任何從大寫A到小寫z的字母 |
| (red|blue|green) | 找出特定的選項,本例為找出red or blue or green |
Metacharacters
| . | 比對任意字元,但換行或結束符號不算 |
| \w | 比對數字和字母,等同於[A-z0-9] |
| \W | 比對非數字和字母,等同於[^A-z0-9] |
| \d | 比對數字,等同於[0-9] |
| \D | 比對非數字,等同於[^0-9] |
| \s | 找出空白字元 |
| \S | 找出非空白字元 |
| \n | 比兌換行字元 |
| \b | 比對字母邊界如空格,ex: /\wy\b/比對"holly"可得到"ly" |
Quantifiers(比對字元的重複次數)
| a? | 比對0個或1個a |
| a+ | 比對1個或多個a |
| a* | 比對0個或多個a |
| a{5} | 比對5個a |
| a{5,10} | 比對5~10個a |
| a{5,} | 比對至少5個a |
| a{,5} | 比對最多5個a |
| a.{5}b | 比對a和b之間有夾5個字元 |
其他特殊字元
| \ | 避開特殊字元,即還原特殊字元,ex:/A\*/可用來比對"A*"\ |
| ^ | 比對輸入列的起始位置,ex: /^A/可比對"Abc"但"aAb"則無法比對成功 |
| $ | 比對輸入列的結束位置,ex: /A$/可比對"cbA"但"CAb"則無法比對成功 |
| (x) | 比對x並將x存成變數RegExp.$1依此類推 |
| (?:x) | 比對x但不存成變數 |
| x|y | 比對x或y,ex: /a+|b+/g可以比對"aaa bb"中的"aaa"和"bb"/ |
3. 常用的function
1. exec(): The exec() method tests for a match in a string.
example:
var strText = "\
I like big butts and I can not lie \
You other brothers can't deny \
That when a girl walks in with an itty bitty waist \
And a round thing in your face \
You get sprung \
Wanna pull up tough \
Cuz you notice that butt was stuffed \
Deep in the jeans she's wearing \
I'm hooked and I can't stop staring \
Oh, baby I wanna get with ya \
And take your picture \
";
var rePattern = new RegExp(
"(big|round|bitty)(?:\\s+)([^\\s]+)",
"gi"
);
var arrMatch = null;
while (arrMatch = rePattern.exec( strText )){
document.write(
arrMatch[ 1 ].toUpperCase() +
" modifies " +
arrMatch[ 2 ].toUpperCase() +
"
"
);
}
相關的參數可以參考MDN
2. test(): The test() method tests for a match in a string.
example:
var str = "The best things in life are free";
var patt = new RegExp("e");
var res = patt.test(str);
3. string.search(re): 可以把regular expression object當成input丟給string的search method
example:
var regexp = new RegExp(pattern, flag); var index = string.search(regexp);
string.replace(re, newStr): 將string符合re的部分換成newStr
example:
var regexp = /world/; var str = "Hello world"; var result = str.replace(regexp,"myworld");
4. 其他技巧
1. Greedy Match: 遇到重複字元時,越多的字元越好
example:
var re = /b.*t/;
2. Minimum Match: 必須在重複字元後面加上一個問號,代表"在可能比對成功的情況下,比對越少越好"
example:
var re = /b.*?t/;
3. 比對email是否輸入正確:
example:
var verifyEmail = /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/;
4. 比對URL:
example:
var url= /^http\://[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(/\S*)?$/;
Reference:
沒有留言:
張貼留言