正则学习

131 阅读1分钟
        • 模糊匹配
  1. 精准匹配
const a = 'abhello'
const isHave = a.test('hello')
  1. 横向模糊(数量)
//{}匹配b3-5个
const testRule = /ab{3,5}c/g
const a = 'abbbc abbbbbc abbbbbbbbbc'
console.log(a.match(testRulr))
  1. 纵向模糊
//[]匹配到哪个都可以
const testRule = /1[345]8/g
const a = '138 123 148'
console.error(a.match(testRule))
//范围的简写
//\为转义字符  -表示范围
const testRule = [1234567abcd]
const testRule = [1\-7a\-d]
  1. 量词
{m,} 出现m次数以上
{m} m次就可以
{m,n} m-n次
+ 至少一次
? 有没有
* 几次都可以
// 惰性匹配?
//只要满足了其中之一条件,就不再做匹配尝试了
var regex = /\d{2,5}?/g;  //对于数字,匹配2-5个,但只要匹配到2个就不再匹配了
var string = "123 1234 12345 123456"; 
console.log( string.match(regex) ); 
// => ["12", "12", "34", "12", "34", "12", "34", "56"]
  1. 常见的简写形式
^ 字符组的第一位放`^`(脱字符),表示求反的概念。[^0-9]不匹配0-9
\d [0\-9] 表示每一个数字
\D [^0\-9]
\w [0-\9a\-zA\-Z] 表示匹配字符
\W [^0-9a-zA-Z]表示匹配非字符 
\s 表示匹配空格
\S 表示匹配非空格
. 表示匹配几乎任意字符
[\d\D] [\s\S] [\w\W] [^] 表示匹配任意字符
  1. 分支匹配 |
//分支匹配是一种惰性匹配,一旦匹配了其中一种情况,就不再做匹配尝试了
//使用分支结构,要注意分支顺序
const testRule = /good | goodbye/g
const str = 'good study,goodbye'
console.log(str.match(testRule))
// good