正则表达式使用单个字符串来描述,匹配一系列符合某个规则的字符串搜索模式。搜索模式可用于文本搜索和文本替换。它用一系列字符定义搜索模式。
用途:

  • 表单输入验证
  • 搜索替换
  • 过滤大量文本文件中的信息
  • 读取配置文件
  • 网页抓取
  • 处理具有一致语法的文本文件,如CSV

    创建方式

  • 字面量

    1. const rex = /pattern/;
  • 构造函数

    1. const rex = new RegExp('pattern');

    模式匹配

    1. 字符集合

    用[]表示,会匹配里面任意一个字符。 ```javascript ‘batdsacatdsfat’.match(/[bcf]at/g) // [‘bat’, ‘cat’, ‘fat’]

‘3.1415926’.match(/[23]/g) // [‘3’,’2’]

  1. <a name="QyueU"></a>
  2. #### 2. 字符范围
  3. [a-z]会匹配a到z之间的任意字符。<br />常见的使用范围的方式如下:
  4. - 部分范围:`[a-f]`,匹配a到f的任意字符;
  5. - 小写范围:`[a-z]`,匹配a到z的任意字符;
  6. - 大写范围:`[A-Z]`,匹配A到Z的任意字符;
  7. - 数字范围:`[0-9]`,匹配0到9的任意字符;
  8. - 符号范围:`[#¥%&@]`
  9. - 混合范围:`[a-zA-Z0-9]`,匹配所有数字、字母;
  10. <a name="m5VbP"></a>
  11. #### 3. 数量字符
  12. `/[a-z]{5}/ig`:匹配所有连续5个字母的单词
  13. ```javascript
  14. 'asdfa dsaf dassda sdd s fdsfsdf'.match(/[a-z]{5}/ig)
  15. // ['asdfa', 'dassd', 'fdsfs']

{m,n}:匹配前面一个字符至少m次至多n次

  1. 'asdfa dsaf dassda sdd s fdsfsdf'.match(/[a-z]{4,5}/ig)
  2. // ['asdfa', 'dsaf', 'dassd', 'fdsfs']

除了可以使用大括号来匹配一定数量的字符,还有三个相关的模式:

  • +:匹配前面一个表达式一次或者多次,相当于{1,}
  • *:匹配前面一个表达式0次或者多次,相当于{0,}
  • ?:单独使用是匹配前面一个表达式0次或者1次,相当于{0,1},如果跟在量词*+?{}后面的时候将会使量词变为非贪婪模式(尽量匹配少的字符)。

    4. 元字符

  • \d:相当于[0-9],匹配任意数字;

  • \D:相当于[^0-9]
  • \w:相当于[0-9a-zA-Z],匹配任意数字、字母和下划线;
  • \W:相当于[^0-9a-zA-Z]
  • \s:相当于[\t\v\n\r\f],匹配任意水平制表符、垂直制表符、换行符、回车符、换页符;
  • \S:相当于[^\t\v\n\r\f],匹配非空白符;

    5. 特殊字符

  • .:匹配除了换行符之外的任何单个字符;

  • \:转义;
  • |:逻辑或;
  • [^]:取非;

    6. 位置匹配

  • \b:匹配一个单词边界,也就是单词和空格间的位置;

  • \B:匹配非单词边界;
  • ^:匹配开头,在多行匹配中匹配行开头;
  • $:匹配结尾,在多行匹配中匹配行结尾;
  • (?=p):匹配p前面的位置;
  • (?!=p):匹配不是p前面的位置; ``javascriptExp is the best ex`.match(/^ex/igm) // [‘Ex’, ‘ex’]

‘dsad dsad dsad dsad’.match(/\b/ig) // [‘’, ‘’, ‘’, ‘’, ‘’, ‘’, ‘’, ‘’] 八个边界 ‘dsad dsad dsad dsad’.match(/\b\w+\b/ig) // [‘dsad’, ‘dsad’, ‘dsad’, ‘dsad’] 四个单词

  1. <a name="Z7soK"></a>
  2. ### 修饰符
  3. - `g`:全局匹配。
  4. - `i`:不区分大小写。
  5. - `m`:多行模式,强制$和^分别匹配每个换行符。
  6. 构造函数创建正则添加修饰符的写法:
  7. ```javascript
  8. let rex = new RegExp('[2b|^2b]','ig')

RegExp实例

实例方法

test、exec校验正则。

test()

用于检测一个字符串是否匹配某个模式。

  1. const rex1 = /a/ig;
  2. const rex2 = /hello/ig;
  3. const str = 'Action speak louder than words';
  4. console.log(rex1.test(str)) // true
  5. console.log(rex2.test(str)) // false

exec()

用于检索字符串中的正则表达式的匹配。

  1. const rex1 = /a/ig;
  2. const rex2 = /hello/ig;
  3. const str = 'Action speak louder than words';
  4. console.log(rex1.exec(str)) // ['A',index:0,input:'Action speak louder than words',groups:undefined]
  5. console.log(rex2.exec(str)) // null

实例属性

RegExp实例内置了一些属性,可以获知一个正则表达式的信息,但是用处不大。

字符串方法

JS中有六种方法支持正则。

1. search()

返回子串起始索引,没有返回-1。

  1. const rex1 = /a/ig;
  2. const rex2 = /p/ig;
  3. const rex3 = /m/ig;
  4. const str = 'Action speak louder than words';
  5. console.log(str.search(rex1)); // 0
  6. console.log(str.search(rex2)); // 8
  7. console.log(str.search(rex3)); // -1

2. match()

  1. const rex1 = /a/ig;
  2. const rex2 = /p/i;
  3. const rex3 = /m/ig;
  4. const str = 'Action speak louder than words';
  5. console.log(str.match(rex1)); // ['A','a','a']
  6. console.log(str.match(rex2)); // ['A',index:0,input:'Action speak louder than words',groups:undefined]
  7. console.log(str.match(rex3)); // null

3. matchAll()

  1. for(const match of 'abcabc'.matchAll(/a/g)) {
  2. console.log(match)
  3. }
  4. // ['a',index:0,input:'abcabc',groups:undefined]
  5. // ['a',index:3,input:'abcabc',groups:undefined]

4. replace()

  1. const rex1 = /A/g;
  2. const str = 'Action speak louder than words';
  3. console.log(str.replace(rex1, 'a'));
  4. // action speak louder than words

5. replaceAll()

替换所有匹配到的项。

6. split()

  1. const rex1 = / /gi;
  2. const str = 'Action speak louder than words';
  3. console.log(str.split(rex1));
  4. // ['Action','speak', 'louder', 'than', 'words']

实际应用

匹配密码

检查密码的格式,其包含至少一个大写字母、小写字母、数字、符号,长度为8-12位。

  1. /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*\W).{8,12)$/g
  2. // 可以匹配
  3. // F3ransd0!

这里主要使用了正则的正向前瞻,语法为(?=pattern),即在目标字符串的相应位置必须有pattern部分匹配的内容,但不作为匹配结果处理,更不会存储在缓冲区内供以后使用。