JavaScript RegExp 物件
JavaScript?RegExp?物件
#RegExp:是正規(guī)表示式(regular expression)的簡(jiǎn)寫。
什麼是 RegExp?
正規(guī)表示式描述了字元的模式物件。
當(dāng)您檢索某個(gè)文字時(shí),可以使用一種模式來(lái)描述要檢索的內(nèi)容。 RegExp 就是這種模式。
簡(jiǎn)單的模式可以是一個(gè)單獨(dú)的字元。
更複雜的模式包括了更多的字符,並可用於解析、格式檢查、替換等等。
您可以規(guī)定字串中的檢索位置,以及要檢索的字元類型,等等。
語(yǔ)法
var patt=new RegExp(pattern,modifiers);
#或更簡(jiǎn)單的方法
var patt=/pattern/modifiers;
模式描述了一個(gè)表達(dá)式模型。修飾符(modifiers)描述了檢索是否為全域,區(qū)分大小寫等。
注意:當(dāng)使用建構(gòu)子建立正規(guī)物件時(shí),需要常規(guī)的字元轉(zhuǎn)義規(guī)則(在前面加上反斜線 \)。例如,以下是等價(jià)的:
var re = new RegExp("\\w+");
var re = /\w+/;
RegExp 修飾符
修飾符用於執(zhí)行不區(qū)分大小寫和全文的搜尋。
i?- 修飾符是用來(lái)執(zhí)行不區(qū)分大小寫的匹配。
g?- 修飾符是用來(lái)執(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ū)分大小寫搜尋"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é)果並傳回真或假。 下面的範(fàn)例是從字串中搜尋字元 "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() 方法會(huì)擷取字串中的指定值。傳回值是被找到的值。如果沒有發(fā)現(xiàn)匹配,則傳回 null。
下面的範(fàn)例是從字串中搜尋字元 "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>