1.实例化正则表达式
1)字面量
var patten = /正则表达式/标记
var patten =/abc/igm
2)构造函数
var patten = new RegExp(“正则表达式”,“标记”);
var patten = new RegExp(“abc”,“igm”);
标记:
i ignoreCase 忽略大小写
g global 全局
m multiline 多行
u unicode 任何Unicode 代码点的转义都会被解释
y sticky 属性反映了搜索是否具有粘性
2.API
静态方法
实例属性
RegExp.prototype.flags 标记
RegExp.prototype.source 正则字符串
RegExp.prototype.ignoreCase
RegExp.prototype.global
RegExp.prototype.multiline
RegExp.prototype.unicode
RegExp.prototype.sticky
实例方法
RegExp.prototype.test(str)
目标字符串中是否可以满足正则表达式的匹配要求
支持全局匹配,当全局匹配的时候,会在正则表达式对象pattern上维护一个变量,lastIndex表示下次开始检索的位置
参数:字符串
返回值boolean
var str = "hello , i am terry, my website is http://134.175.154.93:8888/personal/index.html, ftp url is ftp://172.16.0.20/webui , my phone 18812345432, my friend is larry ,his telephone is 13710009999,his web site is http://www.larry.com/personal/my.index.html , his email is larry@briup. com, my other first is jacky, his telephoen is 17751229900";
var pattern = /1[3578]\d{9}/g;
let result = null;
while(result = pattern.test(str)){
console.log(result);//true ,true,true
}
RegExp.prototype.exec(str)
从目标字符串中获得满足正则表达式匹配要求的子串
支持全局匹配,当全局匹配的时候,会在正则表达式对象pattern上维护一个变量,lastIndex表示下次开始检索的位置。
参数:字符串
返回值:数组
数组元素为匹配的结果
exec的返回值的数组中的第一个元素整体匹配的结果,第二个元素为第一个分组结果,第三个元素为第二个分组结果。
数组属性index表示当前子串在目标串中的位置,input表示目标串,groups表示分组。
var str = "hello , i am terry, my website is http://134.175.154.93:8888/personal/index.html, ftp url is ftp://172.16.0.20/webui , my phone 18812345432, my friend is larry ,his telephone is 13710009999,his web site is http://www.larry.com/personal/my.index.html , his email is larry@briup. com, my other first is jacky, his telephoen is 17751229900";
var pattern = /1[3578]\d{9}/g;
let result = null;
while(result = pattern.exec(str)){
console.log(result[0]);
//18812345432
13710009999
17751229900
}
爬虫:执行爬取价格
¥(\d{2,5}.\d{2})
/<em>\¥</\em><i>(\d{2,5}.\d{2})</i>/ig
3.正则表达式
1.直接量
abc 例如:/abc/ 查找目标串中是否含有abc
2.字符类
[abc] 例如:/[abc]/查找目标串中是否含有abc中任意一个字符
[^abc] 例如:/[^abc]/查找目标串中是否含有除了abc之外任意一个字符
[a - z] a~z中任意一个字符
\w 字母 [a-zA-Z0-9]
\W 非字母[^a-zA-Z0-9]
\d 数字 [0~9]
\D 非数字[^0~9]
\s 空白符
\S 非空白符
多行模式下
^ 以…开始 /^\d\w{3}\d$/
$ 以…结尾 以数字开头数字结尾
3.数量词
数量词一般使用在子表达式(直接量,字符类,分组…)后
/1[3578]\d{9}/
{9} 重复9次
{1,9} 重复1~9次
{1,} 重复1次及以上
{0,} 重复0次及以上
-
等价于{0,}
-
等价于{1,}
? 等价于{0,1}
贪婪匹配
默认式贪婪匹配
{1,9} 优先匹配9次
非贪婪匹配
数量词后添加?就成为了非贪婪匹配
{1,9}? 优先匹配1次
4.选择
子表达式中继添加“|”表示选择
例如:
/hello|hi/
5.数组
获取目标字符串中所有的url,并且分别拿到协议,ip,port,路径
var pattern = /(http|https|ftp|svn)😕/((\d{1,3}.\d{1,3}.\d{1,3}.\d{1,3})|(www.\w{2,}.com)):?(\d{2,5})(/[a-z0-9/]{2,})/ig
6.引用
通过“\数字”对之前分组匹配结果的一种引用。
\1表示对第一个分组匹配结果的引用。
var str = “12hello12”
var str = “871wrold871”
var str =“871wrold888”
var pattern = /(\d{2,})\w+\1/