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

前端 未结 2 1388
我寻月下人不归
我寻月下人不归 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"]
    
    0 讨论(0)
  • 2021-01-27 08:23

    Use capture groups:

    var res1 = '/this/12/that/34'.match(/\/this\/([0-9a-zA-Z]+)\/that\/([0-9a-zA-Z]+)/);
    

    You will get an array containing 3 elements:

    1. The whole match;

    2. 12

    3. 34

    And you can use .slice(1) to remove the first element:

    var res1 = '/this/12/that/34'.match(/\/this\/([0-9a-zA-Z]+)\/that\/([0-9a-zA-Z]+)/).slice(1);
    
    0 讨论(0)
提交回复
热议问题