快速上手正则表达式

105 阅读1分钟

正则表达式(RegExp)是什么

  • RegExp 对象用于将文本与一个规则匹配。

怎么写

// 字面量的方式

let reg = /+86\d{11}/g

// 构造函数的方式

let name = "zhengze"
let reg = new RegExp('www.'+name+'.com','g')

g: global,全文搜索,不添加搜索到第一个结果就会停止搜索 i: ingnore case,忽略大小写,默认大小写敏感 m:multiple lines,多行搜索

RegExP有什么作用

  • 把符合某种规则的子串拿出来
  • 判断字符串是否符合某种规则
  • 按某种规则分割字符串
  • 替换符合某种规则的字符串

前面是简单介绍,现在进入正式学习使用。

简单用法

  • 在正则上使用
let reg = /hello/
reg.text('hello world)
  • 在字符串上使用
let str = 'hello1 world, hello2 world'
str.search(/hello\d/)  // 0
str.match(/hello\d/g) // ['hello1','hello2']
str.replace(/hello\d/g,'hi') // 'hi world, hi world'
str.split(/\s/) // ["hello1", "world,", "hello2", "world"]

// \s,\d 后面会详细说明

对于一些专用字符: ( [ { \ ^ $ | ) ? * + . ,如果需要匹配这些字符,需要转义符 \

单字符匹配

[abcd]匹配⼀个字符,是a b c d中的任 意⼀个
[0-9]匹配⼀个是0到9的数字
[a-zA-Z]匹配⼀个不限制⼤⼩写的字⺟
[^abc]表示⼀个不是字符a或b或c的字符
let reg = /world/
console.log(re.test('hello world')) // true

let reg2 = /#[0-9a-f][0-9a-f][0-9a-f]/
console.log( reg2.test('x#0f0x') ) //true
console.log( reg2.test('x#h8jx') ) //false

let reg3 = /[Ww]rold/
console.log( reg3.test('hi world') ) //true
console.log( reg3.test('hi World') ) //true

console.log(/\[hello\]/.test('[hello]') ) //true

预定义匹配

.等价于 [^\r\n],匹配⼀个除回⻋ 和换⾏以为的任意字符
\d等价于[0-9],匹配⼀个数字字符
\D等价于[^0-9], 匹配⼀个非数字字符
\s等价于[空格\t\n\r\v\f],匹配⼀个空白字符
\S等价于[^空格\t\n\r\v\f],匹配⼀个非空⽩字符
\w等价于[a-zA-Z_0-9],匹配⼀个字母、数字、下划线
\W等价于[^a-zA-Z_0-9],匹配⼀个非单词字符
let str = 'he-llo world, hello world'
let arr1 = str.split(/\s/)
console.log(arr1) //['he-llo', 'world,', 'hello', 'world']

let arr2 = str.split(/\W/).filter(v => v!=='')
console.log(arr2) //['he', 'llo', 'world', 'hello', 'world']
let str2 = str.replace(/\s/g, '')
console.log(str2) //"he-lloworld,helloworld"
数量符
前面的字符出现0次或者1次
+前面的字符出现1次或者多次
*前面的字符出现0次或者多次
{n}前面的字符出现n次
{n,m}前面的字符出现n到m次
{n,}前面的字符出现至少n次
let reg1 = /\d{11}/
console.log( reg1.test('12345678901') ) // true 
let reg2 = /\d{2,4}/ // 注意逗号后没空格
console.log( reg2.test('1234') ) // true 
let reg3 = /https?:\/\/baidu\.com/
console.log( reg3.test('https://baidu.com') ) // true 
console.log( reg3.test('http://baidu.com') ) // true
边界
/^xyz/以xyz开头
/abc$/以abc结尾
/\babc\b/匹配是单词的abc(左右两侧是 字符串开头、结尾、中横线、 空格 )
/\Babc\B/匹配不是单词的abc
let str = 'hello1 world hello2 123456 ruoyu hello3'
str.match(/hello\d/g) // ["hello1", "hello2", "hello3"]
str.match(/^hello\d/g) // ["hello1"]
str.match(/hello\d$/g) // ["hello3"]
let str2 = 'hello1 whello9orld hello2 12-hello8-3456 jirengu ruoyu hello3'
str2.match(/\bhello\d\b/g) // ["hello1", "hello2", "hello8", "hello3"] 
//注意-也⽤于区分单词边界

附上一个更好的博客:30分钟学会正则