1. 預(yù)定義類
. [^\n\r] 除了換行和回車之外的任意字符(“”不行)
\d [0-9] 數(shù)字字符
\D [^0-9] 非數(shù)字字符
\s [ \t\n\x0B\f\r] 空白字符
\S [^ \t\n\x0B\f\r] 非空白字符
\w [a-zA-Z_0-9] 單詞字符
\W [^a-zA-Z_0-9] 非單詞字符
2. 簡單類
1. /string/.test(“string”); // 必須是完整的,只多不能少
/andy/.test(“andy”) // true
/andy/.test(“andylv”) // true
/andy/.test(“an”) // false
2. /[string]/.test(“string”); // 只要包含里面的任何一個(gè)就可以
/[andy]/.test("andy"); // true
/[andy]/.test("an"); // true
/[andy]/.test("ady"); // true
/[andy]/.test("anll"); // true
/[andy]/.test("assd"); // true
/[andy]/.test("ss"); // false
/[3aH8]/.test("ss"); // false
3. 負(fù)向類
中括號(hào)內(nèi),前面加個(gè)元字符^進(jìn)行取反,不是括號(hào)里面的字符(一部分也不行)。
(可以不夠,但是不能多)(不夠和正好,返回false;多了或者沒有返回true)
console.log(/[^abc]/.test('a')); // false
console.log(/[^abc]/.test('gg')); // true
console.log(/[^abc]/.test('aggbc')); // true
注意: 這個(gè)符號(hào) ^ 一定是寫到方括號(hào)里面
4. 范圍類
有時(shí)匹配的東西過多,而且類型又相同,全部輸入太麻煩,我們可以在中間加了個(gè)橫線
console.log(/[a-z]/.test('1111')); // false
console.log(/[A-Z]/.test('aa')); // false
5. 組合類
用中括號(hào)匹配不同類型的單個(gè)字符。
console.log(/[a-m1-5]/.test("b"))//true
6. 量詞 (多個(gè)字母,重復(fù)最后一個(gè))
* (貪婪) 重復(fù)零次或更多 (>=0)
+ (懶惰) 重復(fù)一次或更多次 (>=1)
? (占有) 重復(fù)零次或一次 (0||1) 要么有 要么沒有
{} 重復(fù)多少次的意思 可以有多少個(gè)
您的銀行卡密碼只能是 6位 {6}
{n} n次 (x=n)
{n,} 重復(fù)n次或更多 (x>=n)
{n,m} 重復(fù)出現(xiàn)的次數(shù)比n多但比m少 (n<=x<=m)
* 相當(dāng)于 {0,}
+ 相當(dāng)于 {1,}
? 相當(dāng)于 {0,1}
x | y x 或者 y
() 提啊高權(quán)限,有限計(jì)算
// 封裝自己的trim方法
function trim() {
return str.replace(/(^\s+)|(\s+$)/g,""); // 去掉前面和后面的空格
}
7. 常用的正則表達(dá)式
qq號(hào): /^[1-9][0-9]{4,}$/
手機(jī)號(hào): /^((13[0-9])|(15[^4,\D])|(18[0-9]))\d{8}$/
郵箱: /^[\w\-\.]{5,}\@[\w]+\.[\w]{2,4}$/
座機(jī): /(^0\d{2}-8\d{7}$)|(^0\d{3}-3\d{6}$)/
用戶名: /[\u4e00-\u9fa5]{2,8}/
密碼:
/^[a-zA-Z0-9_\-$]{6,18}$/
/^[A-Za-z0-9]+[_$][A-Za-z0-9]*$/ // 數(shù)字加大小字母加下劃線或者$符
/^([a-z].*[0-9])|([A-Z].*[0-9])|[0-9].*[a-zA-Z]$/ // 數(shù)字加字母
/^([a-z].*[A-Z])|([A-Z].*[a-z])$/ //區(qū)分大小寫字母
// 注意:
/^([a-z].*[A-Z])$/ //表示只要前面是小寫字母和最后面是大寫就行,且中間不管小寫還是大寫都無所謂
// 在這里, . 表示任意字符不包括"",后面接*,表示任意字符0個(gè)或多個(gè)
如: /^([a-z].*[A-Z])$/.test('aaEEAAAc') // false
如: /^([a-z].*[A-Z])$/.test('aaEEAAA') // true
如: /^([a-z].*[A-Z])$/.test('aA') // true
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。