JavaScript RegExp 對象

來源:互聯網
上載者:User

標籤:example   post   表達   匹配   www.   pat   regex   asc   pattern   

1.定義:檢測某個文本時,可以使用一種模式來描述要檢測的內容,RegExp就是這種模式。

2.文法:var patt=new RegExp(pattern,modifiers);或var patt=/pattern/modifiers;

模式描述了一個運算式模型,修飾符描述了檢索是否全域,區分大小寫。

3.RegExp修飾符,用於執行不區分大小寫匹配。

執行個體 1

在字串中不區分大小寫找"W3CSchool"

var str="Visit W3CSchool";
var patt1=/w3cschool/i;

以下標記的文本是獲得的匹配的運算式:

Visit W3CSchool

 

 

 

執行個體 2

全文尋找 "is"

var str="Is this all there is?";
var patt1=/is/g;

以下標記的文本是獲得的匹配的運算式:

Is this all there is?

 

 

 

執行個體 3

全文尋找和不區分大小寫搜尋 "is"

var str="Is this all there is?";
var patt1=/is/gi;

以下 標記的文本是獲得的匹配的運算式:

Is this all there is?

 

 

test()

test()方法搜尋字串指定的值,根據結果並返回真或假。

下面的樣本是從字串中搜尋字元 "e" :

 

執行個體

var patt1=new RegExp("e");
document.write(patt1.test("The best things in life are free"));

由於該字串中存在字母 "e",以上代碼的輸出將是:

true

 

當使用建構函式創造正則對象時,需要常規的字元轉義規則(在前面加反斜線 \)

 

執行個體

var re = new RegExp("\\w+");

 

 

exec()

exec() 方法檢索字串中的指定值。傳回值是被找到的值。如果沒有發現匹配,則返回 null。

下面的樣本是從字串中搜尋字元 "e" :

 

執行個體 1

var patt1=new RegExp("e");
document.write(patt1.exec("The best things in life are free"));

由於該字串中存在字母 "e",以上代碼的輸出將是:

e

 

複製複製:https://www.2cto.com/kf/201601/487274.html

 

JavaScript RegExp 對象

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.