42. Packet capture

Regular grouping:

  1. Change priorities

  2. Group references

    // \2 represents the exact same content as the second group

    // \1 represents the exact same content as the first group

    var reg = / ^ (\ w) \ 1 (\ w) \ 2 $ /; 

    console.log(reg.test("zzff")) // true

    console.log(reg.test("z0f_")) // false

  3. Group capture: When the regular is captured, it not only captures the content matched by the big regular, but also captures the content matched by the small group.

    (?:) in grouping? : means only match without capture

    var reg = /^(\d{2})(\d{4})(\d{4})(\d{2})(\d{2})(?:\d{2})(\d)(?:\d|X)$/;

    var str = "142726199009181211";

    console.log(reg.exec(str)); // ary =  ["142726199009181211","14","2726","1990","09","18","12",'1',"1",index:0, input:"142726199009181211"]

    ary[0] -> the content of the big regular match

    ary[1] -> the content captured by the first group

    ary[2] -> what the second packet captures

    ary[3] -> the content captured by the third group

    ...

    console.log(str.match(reg)); // same result as exec

    var reg = /zhangsan(\d+)/g;

    var str = "zhangsan1234zhangsan3456zhangsan5678";

    // We use exec to execute three times, each time not only to get the big regular match, but also to get the content of the first group match

    console.log(reg.exec(str)); // ->["zhangsan1234","1234"...]

    console.log(reg.exec(str)); // ->["zhangsan3456","3456"...]

    console.log(reg.exec(str)); // ->["zhangsan5678","5678"...]

    // and match can only capture the content of the big regular match

    console.log(str.match(reg)); // ->["zhangsan1234","zhangsan3456","zhangsan5678"]

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325251880&siteId=291194637