JavaScript RegExp 對(duì)象
JavaScript?RegExp?對(duì)象
RegExp:是正則表達(dá)式(regular expression)的簡(jiǎn)寫(xiě)。
什么是 RegExp?
正則表達(dá)式描述了字符的模式對(duì)象。
當(dāng)您檢索某個(gè)文本時(shí),可以使用一種模式來(lái)描述要檢索的內(nèi)容。RegExp 就是這種模式。
簡(jiǎn)單的模式可以是一個(gè)單獨(dú)的字符。
更復(fù)雜的模式包括了更多的字符,并可用于解析、格式檢查、替換等等。
您可以規(guī)定字符串中的檢索位置,以及要檢索的字符類(lèi)型,等等。
語(yǔ)法
var patt=new RegExp(pattern,modifiers);
或更簡(jiǎn)單的方法
var patt=/pattern/modifiers;
模式描述了一個(gè)表達(dá)式模型。修飾符(modifiers)描述了檢索是否是全局,區(qū)分大小寫(xiě)等。
注意:當(dāng)使用構(gòu)造函數(shù)創(chuàng)造正則對(duì)象時(shí),需要常規(guī)的字符轉(zhuǎn)義規(guī)則(在前面加反斜杠 )。比如,以下是等價(jià)的:
var re = new RegExp("\w+");
var re = /w+/;
RegExp 修飾符
修飾符用于執(zhí)行不區(qū)分大小寫(xiě)和全文的搜索。
i?- 修飾符是用來(lái)執(zhí)行不區(qū)分大小寫(xiě)的匹配。
g?- 修飾符是用于執(zhí)行全文的搜索(而不是在找到第一個(gè)就停止查找,而是找到所有的匹配)。
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>php中文網(wǎng)(php.cn)</title> </head> <body> <script> var str = "Visit PHP.cn"; var patt1 = /PHP中文網(wǎng)/i; document.write(str.match(patt1)); </script> </body> </html>
全文查找和不區(qū)分大小寫(xiě)搜索 "is"
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>php中文網(wǎng)(php.cn)</title> </head> <body> <script> var str="Is this all there is?"; var patt1=/is/g; document.write(str.match(patt1)); </script> </body> </html>
test()
test()方法搜索字符串指定的值,根據(jù)結(jié)果并返回真或假。
下面的示例是從字符串中搜索字符 "e" :
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>php中文網(wǎng)(php.cn)</title> </head> <body> <script> var patt1=new RegExp("e"); document.write(patt1.test("The best things in life are free")); </script> </body> </html>
exec()
exec() 方法檢索字符串中的指定值。返回值是被找到的值。如果沒(méi)有發(fā)現(xiàn)匹配,則返回 null。
下面的示例是從字符串中搜索字符 "e" :
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>php中文網(wǎng)(php.cn)</title> </head> <body> <script> var patt1=new RegExp("e"); document.write(patt1.exec("The best things in life are free")); </script> </body> </html>