正则表达式 RegExp 玩法记录

88 阅读2分钟

测试用例

例子 1

let tokensRE = /([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g;
let str = "token=IamAToken";

tokensRE.exec(str);
---------------------------------------
// Chrome Console as follows
(3) ['token=IamAToken', 'token', 'IamAToken', index: 0, input: 'token=IamAToken', groups: undefined]
    0: "token=IamAToken"
    1: "token"
    2: "IamAToken"
    groups: undefined
    index: 0
    input: "token=IamAToken"
    length: 3
    [[Prototype]]: Array(0)

注意:

  1. 正则表达式 ( ) 中的 ?: 符号表示屏蔽掉该 ( ) 分组,让其不在返回数组中和 groups 属性中占位。
  2. 返回数组是标准的 RegExpExecArray 类型,与 ...str.matchAll(new RegExp()) 返回类型一致。...str.match(new RegExp()) 只返回相匹配的字符串。
  3. lastIndex 表示下一次调用 exec 时的字符串开始位置(前提是有g flag)。

例子 2

// 修饰符多了个 d
let tokensRE = /([^\s,;=]+)\s*(?:=\s*([^,;]+))?/dg; 
let str = "token=IamAToken";

tokensRE.exec(str);
---------------------------------------
// Chrome Console as follows
(3) ['token=IamAToken', 'token', 'IamAToken', index: 0, input: 'token=IamAToken', groups: undefined, indices: Array(3)]
    0: "token=IamAToken"
    1: "token"
    2: "IamAToken"
    groups: undefined
    index: 0
    // 多返回了这个 indices (index的复数) 属性
    indices: Array(3)
        0: (2) [015]
        1: (2) [05]
        2: (2) [615]
        groups: undefined
        length: 3
        [[Prototype]]: Array(0)
    input: "token=IamAToken"
    length: 3
    [[Prototype]]: Array(0)

例子 3

// 每个 () 组中加入了组名
tokensRE = /(?<key>[^\s,;=]+)\s*(?:=\s*(?<value>[^,;]+))?/dg;
let str = "token=IamAToken";

tokensRE.exec(str);
---------------------------------------
// Chrome Console as follows
(3) ['token=IamAToken', 'token', 'IamAToken', index: 0, input: 'token=IamAToken', groups: {…}, indices: Array(3)]
    0: "token=IamAToken"
    1: "token"
    2: "IamAToken"
    // 多个 groups 属性,可以按名访问值
    groups: {key: 'token', value: 'IamAToken'}
    index: 0
    // 组中也可以直接访问 indices
    indices: (3) [Array(2), Array(2), Array(2), groups: {…}]
        0: (2) [015]
        1: (2) [05]
        2: (2) [615]
        groups: {keyArray(2), valueArray(2)}
            key: (2) [05]
            value: (2) [615]
        length: 3
        [[Prototype]]: Array(0)
    input: "token=IamAToken"
    length: 3
    [[Prototype]]: Array(0)

注意: 正则括号分组中可以用 ?<...> 给该分组起名,之后可以通过 res.groups.value 访问到相匹配的值。res.indices.groups.value 可以访问到相对应的 index。

正则表达式小贴士

flags in RegExp

d for indices
g for global
i for case insensitive
u for unicode 如果要匹配 emoji, 请使用。
m for multiline, 这使得 ^ $ 字符在各个行都生效。