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
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"]
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:
The whole match;
12
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);