溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

怎么使用JavaScript正則應(yīng)用

發(fā)布時間:2020-07-27 15:23:45 來源:億速云 閱讀:153 作者:小豬 欄目:web開發(fā)

這篇文章主要為大家展示了怎么使用JavaScript正則應(yīng)用,內(nèi)容簡而易懂,希望大家可以學(xué)習(xí)一下,學(xué)習(xí)完之后肯定會有收獲的,下面讓小編帶大家一起來看看吧。

本文實例講述了JavaScript 正則應(yīng)用。分享給大家供大家參考,具體如下:

正則應(yīng)用

正則表達式在web開發(fā)中的常用

郵箱驗證
用戶名驗證
替換字符串某一部分
信息采集,用來分析有效代碼段
...

有規(guī)律的字符串描述

正則表達式是一門獨立的知識,同樣的一段描述,比如,對于email的匹配表達式,在不同的語言是一樣的,但是調(diào)用的函數(shù)不同。

正則表達式--規(guī)則表達式

正則表達式:正則表達式
正則表達式語法:正則表達式語法
正則表達式語言:正則表達式語言

準備性的工作

在js中,如何寫正則表達式。 /RegExp/

在js里,用正則表達式來驗證字符串是否滿足, 使用 reg.test(str);

用正則表達式的exec函數(shù),用來查找匹配的選項,并把查找的值取出。

reg.test(str); 返回true 或者false 。 常在表單驗證中使用。

<from action="xxx.php" id="biaodan">
 <p>請輸入姓名:<input type="text" id="name" /></p> 
 <p>請輸入年齡:<input type="text" id="age" /></p>
 <p><input type="submit" /></p>
</from> 
<script>
 var oBD = document.getElementById('biaodan');
 var oName = document.getElementById('name');
 var oAge = document.getElementById('age');
//表單試圖提交的時候,觸發(fā)onsubmit事件
//這個函數(shù)返回了false,表單不會被提交 
 oBD.onclick = function(){
  //驗證name
  if( !/^[\u4e00-\u9fa5]{2,4}$/.test(oName.value) ) return false; 
  //驗證年齡
  if( !/^\d{2,3}$/.test(oAge.value) ) return false;
  if( parseInt( oAge.value )<10 || parseInt( oAge.value )>104 ) alert('您輸入的年齡不在范圍') return 
false;
  return true;
 }
</script>

exec(); 返回 數(shù)組 或 null。
exec是英語execute的意思,CEO首席執(zhí)行官,E就是executive執(zhí)行的
“執(zhí)行” 把正則式放到字符串上執(zhí)行
每次執(zhí)行結(jié)果按序輸出,不管結(jié)果有幾個,一次只輸出一個 ,如果多次輸出,會保持前面的引用。當(dāng)匹配超過原字符串的時候,會返回null。然后遇到null,指針返回到匹配的字符的第一位。 具有迭代器的感覺。

var str = 'ABCDEFG1234567abcdefg';
var reg = /[a-z]/g;
console.log( a=/[a-z]/g.exec(str) );
var a;
while( a=reg.exec(str) ){ //這邊 null 為 fasle。 exec() 會保持對前面一次的引用。 需要使用 值來賦值。
 console.log( a );
}

使用exec() 找最大子串

var str = 'AAABBBCCCCCCC';
var reg = /(\w)\1+/g;
var maxLength = 0;
var maxLetter = '';
var a;
while( a=reg.exec(str) ){
 if( a[0].length>maxLength ){
  maxLength = a[0].length;
  maxLetter = a[0];
 }
}
console.log( maxLetter );

怎么使用JavaScript正則應(yīng)用

var str='BCDEFG1234567abcdefg';
var reg = /[a-z]/g;
var a;
while( (a=reg.exec(str)) != null ){ //先賦值給a,然后再與后邊判斷。
 console.log( a );
}

怎么使用JavaScript正則應(yīng)用

str.match( reg ); //查找,匹配到,返回數(shù)組
str.split( reg ); //拆分,返回數(shù)組
str.serch( reg ); //查找位置
str.replace( reg,'new str'); //正則替換,返回string

 //測試是否含有hi
var reg = /hi/; //僅看字符串是否有 hi
console.log( reg.test('hello') ); //fasle
console.log( reg.test('this is iqianduan') ); //true
//測試單詞 hi
var reg01 = /\bhi\b/;
console.log( reg01.test('this is') ); //false
console.log( reg01.test('this is, hi,his') );//true

正則表達式 3 句話

要找什么字符?
從哪兒找?
找?guī)讉€?

要找什么字符

字面值, ‘hi' ,就是找‘hi'。

用字符的集合來表示 , [abcd], 指匹配abcd中任意一個

//找不吉利的數(shù)字
//3,4,7
var reg = /[3,4,7]/; //字符集合, 不能使用 /347/ 字面值表示,是表示整體。 
console.log( reg.test('12121212') );//false
console.log( reg.test('12341234') ); //true 

用范圍表示字符 , [0-9] [0123456789] [a-z] [A-Z]

// var reg = /[0123456789]/;
var reg = /[0-9]/;
console.log( reg.test('123afsdf') ); //true
console.log( reg.test('asdf') ); //false
//是否有大寫字母
var reg = /[A-Z]/;
console.log( reg.test('asdf') );//false
console.log( reg.test('Tomorrow is another day') ); //true 

字符簇, 花團錦簇-> 一坨字符。

系統(tǒng)為常用的字符集合,創(chuàng)建的簡寫.
例如:

  • [0-9] --> \d

  • [0-9a-zA-Z_] --> \w .. 域名,注冊用戶名常用的模式.

  • [\t\v\f\r\n] --> \s 空白符.

//是否含有數(shù)字
var reg = /\d/;
console.log( reg.test('123afsdf') ); //true
console.log( reg.test('asdf') ); //false

補集的形式來表示字符集合 在集合前面使用表示補集。

  • [0-9]---> [^0-9] ^ 脫字符號: 念法: caret。['k&aelig;r&#601;t] 。

  • [abcdef]-->[^abcdef]

    //驗證全為數(shù)字
     var reg = /^[0-9]/; //匹配非數(shù)字
     // var reg = /^d/ //字符簇補集
     console.log( reg.test('aaaaa') );//非數(shù)字存在 false
     console.log( reg.test('123aaa') ); //有數(shù)字存在 true

字符簇的補集:

  • d -- > D(非數(shù)字)

  • s --> S(非空白字符)

  • w --> W

  • 任意字符 : . 唯獨不包括換行符

從哪兒找,找到哪兒

b 單詞邊界

/bhi/ --> 從單詞的邊界開始匹配hi。

// 匹配單詞hi,包括hi本身
// var reg = /\bhi.+/;//錯誤
// var reg = /\bhi\w+/; //錯誤。 + --> 至少有 一個
var reg = /\bhi\w*/; 
console.log( reg.exec('this is') ); //null
console.log( reg.exec('his') ); //["his", index: 0, input: "his"]
console.log( reg.exec('history') ); //["history", index: 0, input: "history,hi"]

//匹配進行時的結(jié)尾
var reg = /\b[a-zA-Z]+ing\b/;
console.log( reg.exec('going') );//["going", index: 0, input: "going"]
console.log( reg.exec('1ting.com') );//null
console.log( reg.exec('ing') );//null //2 -> to 4->for 0->zero 

//匹配un前綴的反義詞
//unhappy happy,hungry,sun,unhappy
var reg = /\bun[\w]+\b/;
console.log( reg.exec('happy,hungry,sun,unhappy') ); //["unhappy", index: 17, input: "happy,hungry,sun
,unhappy"]

B 單詞的非邊界

// 把單詞中間的某一個部分取出來。
  // 把中間含有hi的單詞取出,即hi不能在兩端。
var reg = /\Bhi\B/;
console.log( reg.exec('this') ); //["hi", index: 1, input: "this"]
console.log( reg.exec('hi') ); //null

^ creat , 從字符串的起始位置開始匹配

$ 匹配到字符串的結(jié)束位置

從字符串的開頭到結(jié)尾開始匹配,模擬運行順序.

var reg = /^lishi$/;  
console.log( reg.exec('lishinihao') ); null
console.log( reg.exec('lishi') ); //["lisi", index: 0, input: "lisi"]

找多少

*, [0,n] --> {0, }
+ , [1,n] -->{1, }
&#63; , [0,1] -->{0,1}
n {n} {3} a{n} , 字符a準確的出現(xiàn)n次
a{n,} 字符a,至少出現(xiàn)n次。
a{n,m} 字符串a(chǎn),出現(xiàn)n到m次。

模式

以匹配為例,默認情況下,找到一次結(jié)果符合就結(jié)束。
告知匹配過程,一直找,在全文范圍內(nèi)一直找。
g -> 全局模式, global 找所有的,而不是找一次就結(jié)束
i -> 忽略大小寫,ignore

//查找所有中間含有hi的單詞
var reg = /\Bhi\B/gi;
var str = 'shit,hi,this,thit,THIS';
console.log( str.match(reg) ); //["hi", "hi", "hi", "HI"]

確定邊界是什么,那些東西必須有,那些東西可能有可能沒有。配合+,*

//把鏈接換成 #
//<a href="http://www.baidu.com" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" ></a> --> <a href="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" ></a>
//1,不能保留鏈接的文字(反向引用)
//2,不能跨行(貪婪模式)
var reg = /<a[\s]+.*<\/a>/g;
var str = '<a href="http://www.baidu.com" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" ></a>';
console.log( str.replace(reg,'<a href="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >文字</a>') ); 

js不支持單行模式。

//s 單行模式:把整個字符串看成一行

. 代表任意,但不包括換行。

在js里,不支持當(dāng)行模式的情況下,如何換行?

什么樣的模式能代表“所有” 字符串
sS 全部字符 使用一個技巧, 一個集合加補集,就是全集
[dD] [sS] [wW]

var reg = /\<a[\s][\s\S]+<\/a>/g;
var str = '<a href="http://www.baidu.com" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >'+ 
 '</a>';
console.log( str.replace(reg,'<a href="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >文字</a>') );

//s 多行模式:碰到一行就把當(dāng)前的當(dāng)成一個字符串來解析
//把每一行的結(jié)尾的數(shù)字換成 #
//車牌號
//Cx003
//A0008
//B3456
var str = 'Cx003'+
'A0008'+
'B3456';
var reg = /\d+$/gm;
console.log( str.replace(reg,'#') );

貪婪模式

貪婪模式

如果'&#63;'緊跟在在任何量詞*, + , &#63;,或者是{}的后面,將會使量詞變成非貪婪模式(匹配最少的次數(shù)),和默認的貪婪模式(匹配最多的次數(shù))正好相反。
比如,使用/d+/非全局的匹配“123abc”將會返回“123”,如果使用/d+&#63;/,那么就只會匹配到“1”。

當(dāng)正則表達式中包含能接受重復(fù)的限定符時,通常的行為是(在使整個表達式能得到匹配的前提下)匹配盡可能多的字符。以這個表達式為例:a.b,它將會匹配最長的以a開始,以b結(jié)束的字符串。如果用它來搜索aabab的話,它會匹配整個字符串a(chǎn)abab。這被稱為貪婪匹配。

任何量詞后面 跟 &#63; 代表非貪婪模式 , 滿足條件就不找了,小富即安,打完收工。 修飾個數(shù),盡量少找和多找的。

//goooooooooods --> goods
var str = 'goooooooooods,goooods,goooood,gooooo,gooooods';
var reg = /g[o]{3,}&#63;ds/g;
console.log( str.replace(reg,'goods') ); //goods,goods,goooood,gooooo,goods 


欲查

正向欲查

欲查不消耗字符。

//查找進行時的單詞的詞根, 即 不要ing 。 going -> go
var str = 'going,comming,fly';
// var reg = /\b[a-zA-Z]+ing\b/g;
var reg = /\b[\w]+(&#63;=ing)\b/g; // 類似探照燈,先去判斷幾位是否滿足,滿足返回,不滿足繼續(xù)下一位.
console.log( str.match(reg) ); 

怎么使用JavaScript正則應(yīng)用

怎么使用JavaScript正則應(yīng)用

怎么使用JavaScript正則應(yīng)用

滿足 ing ,找到com。

怎么使用JavaScript正則應(yīng)用

不滿足接著走。 看見不滿足條件,并不會一次性調(diào)到ing后面接下去尋找,而是從該處光標繼續(xù)尋找。
已經(jīng)查找的詞是消耗了,下次從該處光標開始尋找。

怎么使用JavaScript正則應(yīng)用

//查找進行時的單詞的詞根, 即 不要ing 。 going -> go
var str = 'going,comming,fly';
// var reg = /\b[a-zA-Z]+ing\b/g;
// var reg = /\b[a-zA-Z]+(&#63;=ing)\b/g; //結(jié)尾\b 是錯誤的, 欲查不消耗字符, 相當(dāng)于/\b[a-zA-Z]+\b/ 這種形式
var reg = /\b[a-zA-Z]+(&#63;=ing)/g; // 類似探照燈,先去判斷幾位是否滿足,滿足返回,不滿足繼續(xù)下一位.
console.log( str.match(reg) ); // ["go", "comm"] 

 

負向欲查

不是誰才行。 往后看一定位數(shù),不是誰才可以。 不要后面是某某某的東西。

怎么使用JavaScript正則應(yīng)用

//查找win98,win95,win32,win2003,winxp -->win98,win32,win2003,winxp
var str = 'win98,win95,win32,win2003,winxp';
var reg = /\bwin(&#63;!95)/g;
console.log( str.match(reg) ); // ["win", "win", "win", "win"]

js不支持,向前正向欲查,向前負向欲查:

//找出 un系列單詞的詞根
var reg = /[\w]+(&#63;<=un)/g;
var str = 'unhappy';
console.log(str.match(reg)); //報錯
var reg = /[\w]+(&#63;<!=un)/g; //向前負向欲查

反向引用

反向引用,也叫后向引用。或者分組或子表達式

一般是整個表達式, 但是中間的部分 有特殊做了描述。 需要的部分特殊處理。使用分組,叫做子表達式。

//把鏈接換成空連接,保持文字信息。
 var str = '<a href="http://www.baidu.com" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >陰天快樂</a>';
 var reg = /<a[\s]+[^>]+>([^<>]+)<\/a>/; //超鏈接的表達式
 console.log( reg.exec(str) ); //["<a href="http://www.baidu.com" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >陰天快樂</a>", "陰天快樂", index: 0
, input: "<a href="http://www.baidu.com" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >陰天快樂</a>"] //能夠把子表達式的東西匹配出來。
 // console.log( str.replacte(reg,'#') );
 /**
  <a[\s]+[^>]>([^<>]+)<\/a> 主要目的是想要中間那一塊
  除了>之外的都可行 , 取> 的補集 [^>]
  中間部分純文字,不含大于號,和小于號。 取小于號和大于號的補集 [^<>]+ / [\s\S]+
 */
 //一般是整個表達式, 但是中間的部分 有特殊做了描述。 需要的部分特殊處理。使用分組,叫做子表達式。
 //匹配html
 // /<\s*(\S+)(\s[^>]*)&#63;>[\s\S]*<\s*\/\1\s*>/
 /*exec為例:
  匹配到的數(shù)組,第0個單元,代表"整個正則表達式的匹配結(jié)果"
  1,2,3,4....N,則代表第N個子表達式匹配的結(jié)果。 //js頂多有9個子表達式。 // ["<a href="http://www.baidu
.com">陰天快樂</a>", "陰天快樂", index: 0, input: "<a href="http://www.baidu.com" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >陰天快樂</a>"]
 */
 console.log( str.replace(reg,'<a href="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >$1</a>') ); //<a href="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >陰天快樂</a>
 
 var str = '<html></html>';
 var reg = /<\s*(\S+)(\s[^>]*)&#63;>[\s\S]*<\s*\/\1\s*>/;
 console.log( reg.exec(str) );
 str.replace(reg,function( $1,$2 ){
  console.dirxml($2); //html
 }); 

如何引用子表達式所匹配的結(jié)果

  • 在正則外邊使用:$N 來匹配 第N個子表達式的匹配結(jié)果。

  • 在正則里邊使用N來 使用第N個子表達式。

以上就是關(guān)于怎么使用JavaScript正則應(yīng)用的內(nèi)容,如果你們有學(xué)習(xí)到知識或者技能,可以把它分享出去讓更多的人看到。

向AI問一下細節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI