Skip to content
Spotify - 每月低于 10 元

第9章 正则

创建正则表达式

js
var str = "where when what"
//1.使用字面量创建正则表达式
var re = /wh/g;	//加上g表示全局匹配

//2.使用正则表达式对象创建
var re2 = new RegExp("wh");

//执行正则表达式
//1.exec()——返回匹配到的内容
console.log(re.exec(str));

//2.test()——返回值为boolean,是否匹配
console.log(re.test(str));	//true

字符匹配

js
var str = `This is str contains 123 
CAPITALIZED letters and _-&^% symbols`

console.log(/T/.test(str));	//true
console.log(/This/.test(str));	//true
console.log(/Thiss/.test(str));	//false

console.log(/12/.test(str));	//true
console.log(/1234/.test(str));	//false

特殊字符匹配

js
var str = `This is str contains 123 
CAPITALIZED letters and _-&^% symbols`
//str.match()用于返回匹配到的字符串

//1."."代表任意一个字符
console.log(str.match(/Th.s/g));	//['This']
console.log(str.match(/1.3/g));	//['123']

//2."\d"代表数字 "\w"代表数字、字母、下划线 "\s"代表空白字符,如"\n","\r"
//大写代表取反
console.log(str.match(/\d/g));  //['1', '2', '3']
console.log(str.match(/\w/g));

匹配次数

js
//1."*"表示匹配任意次
console.log(str.match(/This.*/g));  //['This is str contains 123 ']

//2."+"表示出现一次或多次
console.log(str.match(/t+/g));  //['t', 't', 'tt']

//3."?"表示出现0次或1次
console.log(str.match(/x?/g));

//4."{}"可以指定出现次数
console.log(str.match(/t{2}/g));    //['tt']
console.log(str.match(/\d{1,3}/g));    //['123']

区间、逻辑和界定符

js
//1."[]"出现其中一个,加上^代表非,匹配符号时用\转义
console.log(str.match(/[abc]/g));   //['c', 'a', 'a', 'b']
console.log(str.match(/[0-9]/g));   //['1', '2', '3']
console.log(str.match(/[^0-9]/g));   //匹配非数字

//2."|"代表或
console.log(str.match(/This|contains/g));   //['This', 'contains']

//3."^"在[]外的"^"代表以这个开头
var str = "this is this and that is that"
console.log(str.match(/this/g));    //['this', 'this']
console.log(str.match(/^this/g));    //['this']

//4."$"代表以这个结尾
console.log(str.match(/that/g));    //['that', 'that']
console.log(str.match(/that$/g));    //['that']

//5."\b"代表边界
var str = "athata that"
console.log(str.match(/that/g));    //['that', 'that']
console.log(str.match(/\bthat\b/g));    //['that']

分组

js
//分组用()包裹起来
var str = `this that this and that`
console.log(str.match(/(th).*(th)/));   //'this that this and th'

var str = `aaaab abb cddaa`
console.log(str.match(/(aa){2}/g)); //['aaaa']

字符串替换

js
var str = "This 1is 2an 3apple"
console.log(str.replace(/\d+/g,""));    //This is an apple

var html = `<span>hello</span><div> world</div>`
console.log(html.replace(/<[^>]*>([^<>]*)<\/[^>]*>/g,"$1"));    //hello world

字符串分隔

js
var str = "This | is ,an & apple";
console.log(str.split(/\W+/g)); //['This', 'is', 'an', 'apple']
关注微信公众号搬瓦工 - 美国 CN2 优化线路
你认为这篇文章怎么样?
  • 0
  • 0
  • 0
  • 0
  • 0
  • 0

预览:

评论
  • 按正序
  • 按倒序
  • 按热度
Powered by Waline v3.1.3