regular expression(正则)
基础语法
- '^': 匹配输入的开始,'/^A/'不会匹配"an A"中的A,但会匹配"An E"中的A
- '/'会匹配'eat'中的t,不会匹配'eater'中的t
- '': 匹配一个表达式的0次或多次,等价于{0,},'/bo/'会匹配"booooooed"中的booooooo和"bird"中的b
- '+': 匹配一个表达式1次或多次,等价于{1,}
- '?': 匹配一个表达式0次或者1次,等价于{0,1},如果紧跟在*,+,?或{}的后面,将会使量词变为非贪婪的(匹配尽量少的字符),例如,对 "123abc" 使用 /\d+/ 将会匹配 "123",而使用 /\d+?/ 则只会匹配到 "1"。
- '.': 匹配除换行符之外的任何单个字符,'.n'会匹配 "nay, an apple is on the tree" 中的 'an' 和 'on',但是不会匹配 'nay'。
- '{n}': 匹配一个字符刚好出现了n次,比如, /a{2}/ 不会匹配“candy”中的'a',但是会匹配“caandy”中所有的 a,以及“caaandy”中的前两个'a'。
- '{n,}': 匹配一个字符至少出现n次,例如,/a{2,}/ 匹配 "aa", "aaaa" 和 "aaaaa" 但是不匹配 "a"。
- '\d': 匹配一个数字,例如, /\d/ 或者 /[0-9]/ 匹配"B2 is the suite number."中的'2'。
- '\D': 匹配一个非数字字符。等价于 0-9。例如, /\D/ 或者 /0-9/ 匹配"B2 is the suite number."中的'B' 。
在JavaScript中使用正则
reg.test(str)测试str中是否有符合reg规则的字段,返回boolean类型reg.exec(str)返回str中符合str规则的具体字段,返回array类型str.match(reg)一个在字符串中执行查找匹配的 String 方法,它返回一个数组,在未匹配到时会返回 nullstr.search(reg)一个在字符串中测试匹配的 String 方法,它返回匹配到的位置索引,或者在失败时返回-1
i.g. :
一些例子
1
正则表达式:/^[\w._%+-]+@[\w.-]+.[a-zA-Z]{2,4}$/g
explanation:
^[\w._%+-]+:对于字符串开头进行如下匹配,含有如下字符(a-z || 0-9 || A-Z || . || _ || % || + || -),至少出现一次@匹配@符号[\w.-]+:匹配含有如下字符(a-z || A-Z || 0-9 || . || -),至少出现一次.匹配.[a-zA-Z]{2,4}/g匹配以(a-z || A-Z)结尾,且重复2-4次的字符
visualize:
execution:
2
校验电话号码是否符合格式的sample程序
let reg = /^1[-\s\d]{10}$/;
function checkPhone(phone) {
return reg.test(phone.replace(/[-\s]/g,''));
}
console.log(checkPhone('183 5859 8243'));
console.log(checkPhone('183-5859-8243'));
console.log(checkPhone('18358598243'));
console.log(checkPhone('1756127061'));
console.log(checkPhone('22222222222'));
execution:
3
检验CJK字符
sample
function pareCJK(str) {
let reg = (/[^\u4e00-\u9fa5]+/g);
return !reg.test(str);
}
console.log(pareCJK('中123'));
console.log(pareCJK('中文'));
console.log(pareCJK('😈'));
execution: