- /pattern/attrs
/1232363453/i
regexObj.test(str); 测试正则表达式与指定字符串是否匹配
/2342315435/.test('2131342431');
锚点
匹配一个位置- ^ : 起始位置
/^http:/.test('http://www.163.com');
- $ :结尾位置
/.jpg$/.test('1.jpg');
- -b :单词边界
/\bis\b/.test('that is tom');
- $ :结尾位置
- ^ : 起始位置
字符类
匹配一类字符中的一个
-[abc]:a或b或c/[abc]/.test('aadfsacscvewf');
-[0-9]:一个数字/[0-9]/.test('1');
-[a-z]:一个字母/[a-z]/.test('afdscvdsda');
-.:任一字符(换行除外)/./.test('#%^$^$%$adasc231');
-[^0-9]非数字的一个字符/[^0-9]/.test('abc');
元字符
具有特殊意义的字符
-\d:[0-9]/\d/.test('1ab');
-\D:[^\d]/\D/.test('1ab');
-\s:空白符
-\S:[^\s]
-\w:[A-Za-z0-9]量词
出现的次数
-{m,n}:m到n次/^1\d{10}/.test('12345678892');
-*:{0,}(0到无穷次)/\d*/.test('abc');
-?:{0,1}(0或1次)/https?:/.test('http:www.163.com');
-+:{1,}(1到无穷次)/\d+/.test('1abc');
转义符
需要匹配的字符是元字符的时候
/^http:\/\//.test('http://www.163.com');
/@163\.com$/.test('abc@163.com');
多选分支
代表“或”的意思
/thi(c|n)k$/ === /thi[cn]k/
/\.(jpg|png|jpeg|gif)$/
捕获
保存匹配到的字符串,日后使用
-():捕获/(.+)@(163|126|188)\.com$/
-(?:):不捕获/(.+)@(?:163|126|188)\.com$/
-使用:
- 1, 2,…
-api参数或返回值
- str.match(regexp);
获取匹配的字符串
var url = 'http://blog.163.com/album?id=1#comment';
var reg = /(https?:)\/\/([^\/]+)(\/[^\?]*)?(\?[^#]*)?(#.*)?/;
var arr = url.match(reg);
var protocol = arr[1];
var host = arr[2];
var pathname = arr[3];
var search = arr[4];
var hash = arr[5];
str.replace(regexp/substr, replacement)
替换一个子串
var str = "The price of tomato is 5.";
str.replace(/(\d+)/,"$1.00"); //$1代表获取到的价格
执行结果:"The price of tomato is 5.00."
var str = "The price of tomato is 5, The price of apple is 10.";
str.replace(/(\d+)/g,"$1.00");
执行结果:"The price of tomato is 5.00, The price of apple is 10.00."
var html = '<label>网址:</label><input placeholder="以http://为起始">';
html = html.replace(/[<>]/g,function(m0){
switch(m0){
case '<':
return '<';
case '>':
return '>';
}
});
regexpObj.exec(str);
更强大的检索
-更详尽的结果:index
-过程的状态:lastIndex
var reg = /(.)(\d+)/g;
var scores = 'Tom $88, Nicholas ¥100, jack £38.';
var result;
while(result = reg.exec(scores)){
console.log(result);
console.log(reg.lastIndex);
// reg.lastIndex += 10;
}