js中的Regex

來源:互聯網
上載者:User

標籤:cli   連結   pat   innerhtml   ext   code   單個字元   replace   它的   

1.概念

  什麼是Regex,先來碼上定義,瞭解瞭解。

Regex(英語:Regular Expression,在代碼中常簡寫為regex、regexp或RE)使用單個字串來描述、匹配一系列符合某個句法規則的字串搜尋模式。

Regular:有規律的,Expression:表達。有規律的表達就是Regex(所以為什麼不叫規律運算式呢)。

  它的文法是:

/pattern/modifiers;

 

  先來個小的例子吧:

var p=/this/i

這個例子就是Regex。其中this就是模式,因為Regex是用來檢索的,所以你要檢索什麼,依據什麼來檢索,就是依據這個,比如我要檢索含有this的字串。而i表示insensitivity(不敏感),對大小寫不敏感。

 

2.search()

search()方法是Regex常用的方法之一,顧名思義就是查詢,搜尋的意思。

 1 <body> 2 <p>點擊下面的按鈕,可以出現使用searh()方法查詢“this出現的位置”</p> 3 <button onclick="myfunction()">點擊這裡</button> 4 <p id="there">I do not like this girl</p> 5 <script type="text/javascript"> 6     function myfunction(){ 7         var str="I do not like this girl"; 8         var n=str.search(/this/i); 9         document.getElementById("there").innerHTML=n;10     }11 </script>12 </body>

結果顯示14.

 

3.replace()

replace()方法是Regex常用的方法之一。作用在於替代。

 1 <body> 2 <p>點擊下面的按鈕,可以出現使用replace()方法替代this為that</p> 3 <button onclick="myfunction()">點擊這裡</button> 4 <p id="there">I do not like this girl</p> 5 <script type="text/javascript"> 6     function myfunction(){ 7         var str="I do not like this girl"; 8         var n=str.replace(/this/i,"that"); 9         document.getElementById("there").innerHTML=n;10     }11 </script>12 </body>

 

4.修飾符

在Regex中有多種修飾符。

i 執行對大小寫不敏感的匹配。
g 執行全域匹配(尋找所有匹配而非在找到第一個匹配後停止)。
m 執行多行匹配。

 

 

5.Regex的模式

Regex的模式很多,很強大,這裡不一一介紹,給大家一個連結,有詳細的Regex模式。點擊這裡,或者點擊這裡

【】:表示Regex模式的範圍。比如我要搜尋0-9的話,可以表示成【0-9】。比如abc可以寫成【abc】

 

js中的Regex

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.