RegExp对象
RegExp对象表示正则表达式,在编程过程中经常遇到。
/pattern/attributes // 直接量语法
new RegExp(pattern,attributes); // 创建RegExp对象的语法
参数说明:
pattern:是一个字符串,指定正则表达式的模式或其他正则表达式
attributes:是一个可选的字符串,g(全局匹配)、i(不区分大小写)、m(多行匹配)
RegExp对象的方法
- test方法: 检索字符串中指定的值,返回true或者false
语法: RegExpObject.test(string)
返回值: 如果字符串string中含有与RegExpObject匹配的文字,则返回true,否则返回false
var str = 'world is beautiful!';
var pattern = /is/g;
var result = pattern.test(str); // 想要检测字符创str中是否包含is字符
console.log(result); // => true
- exec方法: 检索字符串中指定的值,返回找到的值,并确定其位置
语法: RegExpObject.exec(string);
var str = 'welcome to china! you will love it';
var patt = new RegExp('china','g');
var res = patt.exec(str);
console.log(res); // => ["china", index: 11, input: "welcome to china! you will love it"]
注:经过测试发现,匹配的正则表达式,需要new RegExp();这种申明,才会返回匹配到的字符串,首次匹配字符串出现的位置,输入。
// 直接写正则匹配效果如下
/china/g.exec('welcome to china! you will love it');
// 输出=> ["china"]
- compile方法:编译正则表达式
compile()用于在脚本执行过程中编译正则表达式,也可以用于改变和重新编译正则表达式。
语法:
RegExpObject.compile(regexp,modifier) // regexp:正则表达式 modifier:规定匹配的类型(g,i,gi等)
var str = 'Every man in the world! Every woman on earth!';
var patt = /man/g;
var str1 = str.replace(patt,'person');
console.log(str1); // ⇒ 'Every person in the world! Every woperson on earth!'
patt = /(wo)?man/g;
patt.compile(patt); // 将正则表达式重新编译 匹配man或者woman
var str2 = str.replace(patt,'person');
console.log(str2); // => 'Every person in the world! Every person on earth!'
支持正则表达式的String对象的方法
- search()方法 :检索与正则表达式相匹配的值
语法: stringObject.search(regexp);
返回值 : stringObject中第一个与regexp相匹配字串的起始位置。若没有匹配到,则返回-1
var str = 'work hard to find job';
console.log(str.search(/to/)); // => 10
- match()方法 :找到一个或多个正则表达式的匹配
语法: stringObject.match(searchVlaue) 或者 stringObject.match(regexp);
返回值:存放匹配结果的数组。该数组的内筒依赖于regexp是否具有全局标识g。
var str = 'The hard part isnt making the decision. Its living with it';
var patt = /the/gi;
console.log(str.match(patt)); // => ["The", "the"]
- replace()方法: 用于在字符串中用一些字符替换另一些字符,或替换一个与正则表达式匹配的字串
语法: stringObj.replace(regexp/substr, replacement);
返回值: 一个新的字符串,用replacement替换了regexp的第一次匹配或所有匹配之后得到的。
var str = 'Welcome to Microsoft!';
console.log(str.replace(/Microsoft/g,'wwwbaidu')); // => Welcome to wwwbaidu!
var name = 'the world is mine'; // 将每个单词的首字母变为大写
var result = name.replace(/\b\w+\b/g,function(word){ // \b匹配一个字边界,即字与空格间的位置
return word.substring(0,1).toUpperCase()+word.substring(1); // The World Is Mine
});
在书写正则表达式的时候,可能会包含变量,此时正则表达式需要写成:
var v = "bl";
var re =new RegExp("^\\d+" + v + "$","g"); // re为/^\d+bl$/gim
分组语法 捕获
(exp)
匹配exp,并捕获文本到自动命名的组里
(?<name>exp)
匹配exp,并捕获文本到名称为name的组里,也可以写成(?’name’exp)
(?:exp)
匹配exp,不捕获匹配的文本
位置指定
(?=exp)
匹配exp前面的位置
(?<=exp)
匹配exp后面的位置
(?!exp)
匹配后面跟的不是exp的位置
(?<!exp)
匹配前面不是exp的位置