正则的基础用法

一、正则的作用:

用于匹配和操作文本的工具

二、基本用法:

//匹配字母

const reg1 = /[a-zA-Z]/

//匹配数字

const reg2 = /\d/

//匹配非数字

const reg3 = /\D/

//空格

const reg4 = /\s/

//字母,数字,下划线

const reg5 = /\w/

//特殊字符

const reg6 = /[!@#$%^&*]/

//非字母匹配

const reg7 = /[^a-zA-Z]/

三、正则方法

//test()检查一个字母是否与正则表达式匹配,返回布尔值

const reg8 = /hello/
const str1 = 'hello,world'
console.log(reg8.test(str1))

//match()方法,在字符串中搜索匹配正则表达的内容,返回数组或null

console.log(str1.match(reg8))

//search()在字符串中搜索匹配正则表达式的内容,返回匹配的索引或-1 负

const reg9 = /world/
console.log(str1.search(reg9))//-1代表找不到

//replace()将匹配正则表达式的内容替换为指定字符串,并返回替代后的字符串

console.log(str1.replace(reg9,'1111'))

//split()根据正则表达式将字符串分割成数组

console.log(str1.split(/\s/))

四、正则位置匹配

//匹配字符串开始的位置

const str2 = 'hello world'
const str3 = 'AAAhello world'
const reg10 = /hello/
const reg11 = /^hello/
console.log(reg10.test(str2),reg10.test(str3))
console.log(reg11.test(str2),reg11.test(str3))

//举例,匹配手机号

//const phoneNum = '13312341234'
const phoneNum = '12312341234ddd'
const phoneReg = /^1\d{10}$/ //^前面无
console.log(phoneReg.test(phoneNum))

//如上,$代表结束位置

// \b 代表匹配单词边界

// \B非单纯边界

const reg12 = /\bworld\b/
console.log(reg12.test(str2))//hello world
const str4 ='helloworld'
console.log(reg12.test(str4))


五、量词

 

匹配前一个字符出现0次或多次

 /ab*c/ 匹配ac,abc,abbbc等
 

 +匹配前一个字符出现1次或多次

 /ab+c/ 匹配abc,abbbc,不匹配ac
 

 ?匹配前一个字符出现0次或1次

 /ab?c/ 匹配ac,abc,不匹配abbbc
 
 {n}匹配前一个字符出现n次,多了不行,少也不行
 
 {n,}匹配前一个字符,至少n次
 
 {n,m}出现n~m次
 

六、贪婪匹配和惰性匹配

const string = 'aaaaa'
const greedyPattern = /a+/ //贪婪匹配 尽可能足够多
const lazyPattern = /a+?/ //惰性匹配 只一个

console.log(string.match(greedyPattern))
console.log(string.match(lazyPattern))

七、字符类别

[abc]匹配的是a或b或c
[a-z]
[A-Z]
[a-zA-Z]
[0-9]
[0-9a-fA-F]//匹配十六进制字符
[^abc]//非a非b非c

八、分组

(abc)匹配abc字符串

(ab)+ 匹配连续出现的ab字符串,如ab,abab,ababab等
(a|b) //等同于[ab]
(abc|def)
九、捕获
捕获:小括号的嵌套
(a(b)c) 分组的里面又有一个分组,就是所谓捕获

十、修饰符

//1.i 不区分大小写

const reg13 = /hello/i
console.log(reg13.test("Hello"))

//2.全局匹配 g 是global,全球,全局的,所有都会被匹配

console.log("Hello,hello,HELLO".match(reg13))

//3.m代表的是多行匹配

const pattern = /^hello/im;
console.log("Hello\nhellohello".match(pattern));//输出:["Hello","hello"]

























</script>
posted @ 2023-07-07 08:21  山谷回响  阅读(25)  评论(0)    收藏  举报