JavaScript RegExp 對象
RegExp:是正則表達式(regular expression)的簡寫。
完整 RegExp 對象參考手冊
請查看我們的 JavaScript RegExp 對象的參考手冊,其中提供了可以與字符串對象一同使用的所有的屬性和方法。
這個手冊包含的關(guān)于每個屬性和方法的用法的詳細(xì)描述和實例。
什么是 RegExp?
正則表達式描述了字符的模式對象。
當(dāng)您檢索某個文本時,可以使用一種模式來描述要檢索的內(nèi)容。RegExp 就是這種模式。
簡單的模式可以是一個單獨的字符。
更復(fù)雜的模式包括了更多的字符,并可用于解析、格式檢查、替換等等。
您可以規(guī)定字符串中的檢索位置,以及要檢索的字符類型,等等。
語法
或更簡單的方法
var patt=/pattern/modifiers;
模式描述了一個表達式模型。
修飾符(modifiers)描述了檢索是否是全局,區(qū)分大小寫等。
注意:當(dāng)使用構(gòu)造函數(shù)創(chuàng)造正則對象時,需要常規(guī)的字符轉(zhuǎn)義規(guī)則(在前面加反斜杠 \)。比如,以下是等價的:
var re = new RegExp("\\w+"); var re = /\w+/;
RegExp 修飾符
修飾符用于執(zhí)行不區(qū)分大小寫和全文的搜索。
i - 修飾符是用來執(zhí)行不區(qū)分大小寫的匹配。
g - 修飾符是用于執(zhí)行全文的搜索(而不是在找到第一個就停止查找,而是找到所有的匹配)。
實例
<!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.cn/i; document.write(str.match(patt1)); </script> </body> </html>
運行實例 ?
點擊 "運行實例" 按鈕查看在線實例
實例
<!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>
運行實例 ?
點擊 "運行實例" 按鈕查看在線實例
實例
<!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/gi; 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>
運行實例 ?
點擊 "運行實例" 按鈕查看在線實例
當(dāng)使用構(gòu)造函數(shù)創(chuàng)造正則對象時,需要常規(guī)的字符轉(zhuǎn)義規(guī)則(在前面加反斜杠 \)
實例
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>php中文網(wǎng)(php.cn)</title> </head> <body> <script> var str = 'php'; var patt1 = new RegExp('\\w', 'g'); // 有轉(zhuǎn)義作為正則表達式處理 var patt2 = new RegExp('\w', 'g'); // 無轉(zhuǎn)義作為字符串處理 var patt3 =/\w+/g; // 與 patt1 效果相同 document.write(patt1.test(str)) //輸出 true document.write("<br>") document.write(patt2.test(str)) //輸出 false document.write("<br>") document.write(patt3.test(str)) //輸出 true </script> </body> </html>
運行實例 ?
點擊 "運行實例" 按鈕查看在線實例
exec()
exec() 方法檢索字符串中的指定值。返回值是被找到的值。如果沒有發(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>
運行實例 ?
點擊 "運行實例" 按鈕查看在線實例