How to extract “parts” of a String according to some RegExp pattern?

前端 未结 2 1390
我寻月下人不归
我寻月下人不归 2021-01-27 07:42

In JavaScript, given a regexp pattern and a string:

var pattern = \'/this/[0-9a-zA-Z]+/that/[0-9a-zA-Z]+\';
var str = \'/this/12/that/34\';

How

2条回答
  •  滥情空心
    2021-01-27 08:16

    In Regex, you can use parentheses to delimit "capture groups". These can then be retrieved from your match. It should also be noted that regexes are literals in JavaScript, you must not put quotes around them (slashes are used instead) and you must escape properly.

    For example, if you use this regex:

    var pattern = /\/this\/([0-9a-z]+)\/that\/([0-9a-z]+)/i;
    // that final "i" avoids the need to specify A-Z, it makes the regex ignore case
    

    Now when you match it against your string:

    var match = str.match(pattern);
    

    Your result will look like:

    ["/this/12/that/34","12","34"]
    

    Note that the first index of the array will always be your entire match. You can use .shift to slice it off:

    match.shift();
    

    Now match looks like:

    ["12","34"]
    

提交回复
热议问题