正则表达式
作者:互联网
语法
/正则表达式主体/修饰符
search()
var str = "Visit Runoob!";
var n = str.search(/Runoob/i);
// n=6
replace()
var str = 'Visit Microsoft!'
var txt = str.replace(/microsoft/i,"Runoob");
// txt = Visit Runoob!
修饰符
- i 忽略大小写
- g 全局匹配,而非找到第一个匹配后停止
- m 执行多行匹配
模式
- [abc] 查找方括号之间的任何字符
- [0-9] 查找从0至9的数字
- (x|y) 查找任何以|分隔的选项
元字符(元字符是拥有特殊含义的字符)
- \d 匹配数字
- \s 匹配空白字符
- \S 匹配不是空白符的字符
- \w 匹配字母或数字或下划线或汉字
- \W 匹配不是字母或数字或下划线或汉字的字符
- \b 匹配单词边界
- \B 匹配不是单词开头或结束的位置
- \uxxxx 查找以十六进制数xxx规定的Unicode字符
- ^ 匹配字符串的开始
- $ 匹配字符串的结束
- [^aeiou]匹配除了aeiou这几个字母以外的任意字符
量词
- n+ 匹配任何包含至少一个n的字符串
- n* 匹配任何包含零个或多个n的字符串
- n? 匹配任何包含另个或一个n的字符串
- {n} 重复n次
- {n,} 重复n次或更多次
- {n,m} 重复n次到m次
懒惰限定符
- *? 匹配0次或多次但尽可能少的匹配
- +? 匹配1次或多次但尽可能少的匹配
- ?? 匹配0次或1次但尽可能少的匹配
- {n,m}? 匹配n到m次但尽可能少的匹配
- {n,}? 匹配n次或更多次但尽可能少的匹配
使用RegExp对象
test()
test() 方法用于检测一个字符串是否匹配某个模式,如果字符串中含有匹配的文本,则返回 true,否则返回 false。
var patt = /e/;
const res = patt.test("The best things in life are free!");
// res = true
exec()
exec() 方法用于检索字符串中的正则表达式的匹配。
该函数返回一个数组,其中存放匹配的结果。如果未找到匹配,则返回值为 null。
const res = /ee+/.exec("The best things in life are free!");
// res = ['ee', index: 30, input: 'The best things in life are free!', groups: undefined]
标签:字符,匹配,正则表达式,res,尽可能少,var,字符串 来源: https://www.cnblogs.com/JianXin1994/p/16188513.html