正則表達式是一個對象,主要是用於匹配字符串中字符組合的模式。
特色javascript
在javascript中,能夠經過兩種方式建立正則表達式
test()是正則表達式對象的方法,用來檢驗字符串是否符合該規則,返回值爲true或者false.
注意:正則表達式不須要加引號,無論是字符串或值型html
1.經過RegExp對象的方式建立正則表達式java
var 變量名 = new RegExp(/表達式/)
2.經過字面量建立正則表達式
var 變量名 = /表達式/
註釋中間放表達式就是正則表達式字面量ide
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>正則表達式</title> </head> <body> </body> <script> //1.利用RegExp對象來建立正則表達式 let regexp = new RegExp(/123/); console.log(regexp) //2.利用字面量的方式來建立 let regexp2 = /123/; console.log(regexp2) //test()方法用來檢驗字符串參數是否符合正則表達式的規則 console.log(regexp.test(123)); console.log(regexp2.test(123)); </script> </html>
### 正則表達式的組成工具
一個正則表達式能夠由簡單的字符組成,好比/abc/,也能夠是簡單與特殊字符的組合,如 ^ 、$ 、+ 等。
特殊字符很是多,能夠參考:測試
正則表達式中的邊界符(位置符)用來提示字符所在的位置,主要有兩個字符
若是^與$同時存在,則表明精準匹配ui
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>正則表達式之邊界符</title> </head> <body> </body> <script> let regexp = /abc/; //test()方法裏面的參數只要包含abc字符,即爲true console.log(regexp.test('abc'))//true console.log(regexp.test('abcd'))//true console.log(regexp.test('abcde'))//true let regexp2 = /^abc/ //test()方法裏面的參數必須以abc開頭,即爲true console.log(regexp.test('abc'))//true console.log(regexp.test('bacd'))//false console.log(regexp.test('abcde'))//true let regexp3 = /^abc$/ //test()方法裏面的參數必須是abc,即爲true console.log(regexp.test('abc'))//true console.log(regexp.test('bacd'))//false </script> </html>
[]:表示有一系列的字符能夠選擇,只要匹配其中一個即可以了spa
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>正則表達式之字符類</title> </head> <body> </body> <script> let regexp = /[abc]/ //只需包含a或b或c的字符 返回值便可true console.log(regexp.test('name')); console.log(regexp.test('body')); console.log(regexp.test('chinese')); console.log('-----------------------------------') let regexp2 = /^[abc]$/ //三選一,只能是a或b或c中的任意字符,返回值爲true. console.log(regexp2.test('a')); console.log(regexp2.test('b')); console.log(regexp2.test('c')); console.log(regexp2.test('d'));//false console.log('-----------------------------------') let regexp3 = /^[a-z]$/ //多選一,只能是26個小寫字母中任意一個字符,返回值爲true. console.log(regexp3.test('a')); console.log(regexp3.test('b')); console.log(regexp3.test('c')); console.log(regexp3.test('d')); console.log('-----------------------------------') let regexp4 = /^[a-zA-Z0-9_-]$/ //多選一,只要是26個小寫字母或26個大寫字母或0-9和_-中任意一個字符,返回值爲true. console.log(regexp4.test('A')); console.log(regexp4.test('b')); console.log(regexp4.test('0')); console.log(regexp4.test('!')); //false console.log('-----------------------------------') let regexp5 = /^[^a-zA-Z0-9_-]$/ //多選一,[]裏面的^是取反的意思,只要不是[]裏面的字符 都爲true console.log(regexp5.test('A')); console.log(regexp5.test('b')); console.log(regexp5.test('0')); console.log(regexp5.test('!')); //true console.log('-----------------------------------') </script> </html>