一基础知识
方括号范围
在ascii码表中是连续的才可以用“-”写在方括号里面
[ ]在某个范围
[^]不在这个范围
(|)或者
小知识:
Ascii码表
A65
a97
量词
+最少一个
*0个或者多个
?0个或者1个
{x}匹配x次
{x,y}匹配最少x最多y
{x,}匹配至少x次
^n 这里的n代表字符串,只能以n开头的字符串
n$ 这里的n代表字符串,只能以n结尾的字符串
?=n这里的n代表字符串,任何其后紧接指定字符串 n 的字符串
?!n
这两个不好理解贴代码:
var str = "this is all is dog is all";
var reg = /is(?= all)/g;
var result;
while((result=reg.exec(str))!=null)
{
console.log(result);
}
结果为:
![](https://img.haomeiwen.com/i3729817/1173b7fd9fe4abf7.png)
贪婪模式
str.match(/.*/g);
["wo shi ha12 en 3", ""]
开放模式
元字符
.单个字符
\w 单词字符,数字,下划线
\W
\d数字
\D
\s空白字符
\S
\b单词边界
\B
二两种定义方式
1.正则表达式的方法 / /i g(忽略大小写,全局匹配)
2.var reg=new RegExp(pattern,attributes);
三RegExp的方法(只有三个)
reg.test(string)
reg.exec()
reg.compile()
如代码测试:
var str="this is a first reg test.";
var reg=new RegExp("is","g");
console.log(reg.test(str));
var result;
var i=0;
while((result = reg.exec(str))!=null){
console.log(result);
i++;
if(i>10)break;
}
输出结果为:
![](https://img.haomeiwen.com/i3729817/c60cebec0b2016a4.png)
想了解更多这三个方法:请参考 RegExp对象的三个方法.
顺便贴一张牛课网的试题:
![](https://img.haomeiwen.com/i3729817/9b1fd7c6ec5fd085.png)
三支持正则表达式的string的方法
search()
Index()
match() 用的比较多,找到内容若干个
replace() 查找并替换
split() 把字符串分割成数组
未完,待更
网友评论