正则表达式用于对字符串模式匹配及检索替换,是对字符串执行模式匹配的强大工具。
一、正则表达式的语法
二、修饰符
修饰符 | 描述 |
g | 全局匹配(查找所有匹配而非在找到第一个匹配后停止) |
i | 对大小写不敏感的匹配 |
m | 多行匹配 |
u | (ES6新增)“Unicode”模式,用来正确处理大于\uFFFF的Unicode字符 |
y | (ES6新增)“粘黏”(sticky)修饰符,与g修饰符类似,也是全局匹配,但是g修饰符只要剩余位置中存在匹配就行,而y修饰符会确保匹配必须从剩余的第一个位置开始。 |
s | (ES6新增)dotAll模式,即点(.)代表一切字符,而不是常规意义下的除行终止符以外的任意单个字符。 |
三、RegExp对象方法
(1)exec()
语法:RegExpObject.exec(string)
作用:检索字符串中指定的值,并以数组的形式返回找到的值
/\s*([0-9]+)\s*/.exec(' 1 ');//返回[" 1 ","1"]
返回数组的第一项是\s*([0-9]+)\s*匹配到的字符串" 1 ",第二项是捕获组([0-9]+)捕获到的分组字符串"1"。
(2)compile()
语法:RegExpObject.compile(regexp, modifier)
作用:既可用于脚本执行过程中编译正则表达式,也可用于改变和重新编译正则表达式
let str = "cat is black, dog is yellow."; let pattern = /cat/g; console.log(str.replace(pattern, 'CAT'));//CAT is black, dog is yellow. let anotherPattern = /dog/g; pattern.compile(anotherPattern); console.log(str.replace(pattern, "DOG"));//cat is black, DOG is yellow.
(3)test()
语法:RegExpObject.test(string)
作用:检测一个字符串是否包含匹配指定的模式的子串,如果有返回true,否则返回false
/hello/g.test("hello world");//true /Hello/g.test("hello world");//false
四、String对象支持正则表达式的方法
(1)search()
语法:String.search(regexp|string)
作用:当参数为字符串时,与indexOf()方法一样,返回子串在字符串中的起始位置;当参数为正则表达式时,检索与正则表达式相匹配的子串,返回子串在字符串中的起始位置。如果没有找到,则返回-1。
"hello world".search(/world/g);//6 "hello world".search(/word/g);//-1
(2)match()
语法:String.match(regexp)
作用:在字符串内检索指定的值,找到一个或多个匹配模式的子串
'CAT bat MaT'.match(/at/gi);//返回["AT", "at", "aT"]
(3)replace()
语法:String.replace(searchValue, newValue)
作用:替换字符串中与searchValue相匹配的子串或者模式为newValue
PS:该方法不会改变原始字符串
let str = "hello world"; console.log(str.replace("world", "WORLD"));//hello WORLD console.log(str);//hello world console.log(str.replace(/hello/g, "HELLO"));//HRLLO world console.log(str);//hello world
(4)split()
语法:String.split(seperator, limit)
作用:根据seperator将字符串分割成字符串数组
参数说明:seperator为分割符,是字符串或者正则表达式,不在返回值中;limit为指定返回数组的长度
PS:I. 若seperator为空字符串(""),则将string被分割为单个字符的数组;
II. 此方法不改变原始字符串。
let str = "abbbbbcbbbd"; console.log(str.split(/b+/));//["a","c","d"] console.log(str);//abbbbbcbbbd
五、常用正则表达式(模式)
(1)验证是否小数的模式
let pattern= /^\d+\.\d+$/;
(2)验证是否中文名称的模式
let pattern=/^[\u4E00-\u9FA5]{2,4}$/;
(3)验证是否电话号码格式的模式
let pattern= /^((0\d{2,3}-\d{7,8})|(1[3584]\d{9}))$/;
(4)验证是否邮箱地址的模式
le pattern=/^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+$/;