zoukankan      html  css  js  c++  java
  • 04. 使用元字符(学习笔记)

    4. 正则表达式必知必会-使用元字符

    4.1 对特殊字符进行转义

    . 表示匹配任意一个单字字符。
    [] 表示匹配字符集

    const str = 'const arr = []; if (arr[0] === 0) {}';
    const reg = /arr[0]/g; // <-- 想匹配 arr[0] 这个内容,但是 [0] 表示包含 0 的字符集,只能匹配 arr0
    let match;
    while ((match = reg.exec(str))) { // <-- 匹配不到
      console.log(match);
    }
    

    加上反斜杠可以将元字符转义。

    const str = 'const arr = []; if (arr[0] === 0) {}';
    const reg = /arr[0]/g; // <-- 将 [] 进行转义
    let match;
    while ((match = reg.exec(str))) {
      console.log(match);
    }
    // ["arr[0]", index: 20, input: "const arr = []; if (arr[0] === 0) {}", groups: undefined]
    

    也是一个元字符,使用它本身时,也需要转义:。

    在一个完整的正则表达式里, 后面永远跟着一个字符,否则会报错。

    4.2 匹配空白字符

    元字符 说明
    [] 回退并删除一个字符
    f 换页符
    换行符
    回车符
    制表符
    v 垂直制表符
    const str = '01 test01 
    
    ' + '02 test02 
    
    ' + '03 test03';
    console.log(str);
    /*01 test01 ↵
     *02 test02 ↵
     *03 test03
    */
    const reg = /
    
    /g;
    console.log(str.replace(reg, '')); // 01 test01 02 test02 03 test03
    

    4.3 匹配特定的字符类型

    4.3.1 匹配数字(与非数字)

    元字符 说明
    d 匹配任何一个数字字符,等价于 [0-9]
    D 匹配任何一个非数字字符,等价于 [^0-9]
    const str = 'const arr = [];
    console.log(arr[0], arr[1], arr[2]);';
    const reg = /arr[d]/g;
    let match;
    while ((match = reg.exec(str))) {
      console.log(`匹配项: ${match[0]}, index: ${match.index}`);
    }
    // 匹配项: arr[0], index: 28
    // 匹配项: arr[1], index: 36
    // 匹配项: arr[2], index: 44
    

    4.3.2 匹配字母和数字(与非字母和数字)

    元字符 说明
    w 匹配任何一个字母数字字符(不区分大小写)或下划线字符,等价于 [a-zA-Z0-9_]
    W 匹配任何一个非字母数字字符或非下划线字符,等价于 [^a-zA-Z0-9_]

    4.3.3 匹配空白字符(与非空白字符)

    元字符 说明
    s 匹配任何一个空白字符,等价于 [f v]
    S 匹配任何一个非空白字符,等价于 [^f v]

    注意:[] 比较特殊,没有包含了 s 中。

    4.3.4 匹配十六进制或八进制数值

    1. 使用十六进制值

    正则表达式里,十六进制要用前缀 x 来表示。

    x0A 对应于 ASCII 码中的 10(换行符),等价于 。

    2. 使用八进制值

    使用前缀 表示。

    4.4 使用 POSIX 字符类

    JavaScript 不支持。

  • 相关阅读:
    kubernetes添加不了google apt-key
    The command 'xxx' returned a non-zero code: 100
    gitlab autuo devops
    zabbix监控流程图
    xshell全局设置配色方案
    设置行,列尺寸,权重weight(tkinter,Python3.x)
    Tkinter 的 Text 组件
    Python字符串颜色输出
    tkinter Frame relief属性演示
    Tkinter 的组件 PanedWindow
  • 原文地址:https://www.cnblogs.com/lwl0812/p/11216931.html
Copyright © 2011-2022 走看看