正则笔记

split()方法

简介:用于把一个字符串按符合匹配条件的方式分割成一个字符串数组。

var str="How 1are 2you 3doing 4today?";
var a=str.split(" ");
var b=str.split(" ",2);
var c=str.split(/\d/);
var d=str.split(/\d/,3);
console.log(a);//["How", "1are", "2you", "3doing", "4today?"]
console.log(b);//["How", "1are"]
console.log(c);//["How ", "are ", "you ", "doing ", "today?"]
console.log(d);//["How ", "are ", "you "]

replace()方法

简介:用于在字符串中用一些字符替换另一些字符,或替换一个与正则表达式匹配的子串。原字符串不变,创建一个新的字符串

替换第一个和替换全部符合正则的子串
var str="hello world! hello world! hello world!"; 
var a=str.replace(/hello/,"Runoob");
var b=str.replace(/hello/g,"Runoob");
console.log(a)
console.log(b)

test()方法(true/false)

介绍:方法用于检测一个字符串是否匹配某个模式;如果字符串中有匹配的值返回 true ,否则返回 false。

var str="Hello world!";
//查找"Hello"
var patt1=/Hello/g;
var result1=patt1.test(str);
console.log(result1); //true
//查找 "Runoob"
var patt2=/Runoob/g;
var result2=patt2.test(str);
console.log(result2); //false

match()方法

简介:match() 方法可在字符串内检索指定的值,或找到一个或多个正则表达式的匹配

例子

  • 简单匹配(单词匹配)
var str = 'The car parked in the garage.';
var res = str.split('the');
console.log(res);
结果:
 ["The car parked in ", " garage."]
  • 点是元字符中最简单的例子。 .匹配任意单个字符,但不匹配换行符。 例如,表达式.ar匹配一个任意字符后面跟着是a和r的字符串。
var str = 'The car parked in the garage.';
var res = str.match(/.ar/g);
console.log(res);
结果:
["car", "par", "gar"]
  • 字符集[]
var str = 'Thecar parked in the garage.';
var res = str.match(/[Tt]he[c ]/g);
console.log(res);
结果:
 ["Thec", "the "]
  • 否定字符集[^]
var str = 'Thecar parked in the garage.';
var res = str.match(/[^p]ar/g);
console.log(res);
结果:
["car", "gar"]
  • 重复次数 +,* or ?
*
var str = 'The fat cat sat on the concatenation.';
var res = str.split(/[\s]on\s*/g);
console.log(res);
结果:
["The fat cat sat", "the concatenation."]

?
var str = 'The car is parked in the garage.';
var res = str.split(/[T]?he/g);
console.log(res);
结果:
["", " car is parked in t", " garage."]
  • {} 号
表达式 [0-9]{2,3} 匹配最少 2 位最多 3 位 0~9 的数字。

2,3位数字
var str = 'The number was 9.9997 but we rounded it off to 10.0.';
var res = str.split(/[0-9]{2,3}/g);
console.log(res);
结果:
["The number was 9.", "7 but we rounded it off to ", ".0."]

3位数字
var str = 'The number was 9.9997 but we rounded it off to 10.0.';
var res = str.split(/[0-9]{3}/g);
console.log(res);
结果:
["The number was 9.", "7 but we rounded it off to 10.0."]
  • ^和$
var str = 'The fat cat. sat. on the mat.';
var res = str.split(/at\.$/);
console.log(res);
结果:
["The fat cat. sat. on the m", ""]

Git正则链接

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值