Reputation: 2411
I am trying to extract a set of numbers from a url. The string is betwen the word "region" and word "all". The url is : http://my.site.com/theme/feature/region/227-84/all/country-south
The regular expression which I have built is :
var tmp = $(this).attr('link').match("(?=region/).*?(?=/all)");
The regex is extracting the correct portion of numbers but is always sticking the region to numbers so the extracted string become :
"region/227-84"
While I wannt to get only the numbers:
"227-84"
Upvotes: 1
Views: 146
Reputation: 1
If you already know that the size of the string you are looking for you could do this:
......(?=\/all)
Upvotes: 0
Reputation: 240938
It's including the substring "region/" because the positive lookahead (?=region\/)
is matching the character before "region/". Since JavaScript doesn't have lookbehinds, the easiest option would be to remove the lookaheads and use a capturing group in order to extract the middle portion:
/region\/([^\/]*)\/all/
or if there are slashes between the patterns:
/region\/(.*?)\/all/
Usage:
var match = $(this).attr('link').match(/region\/([^\/]*)\/all/);
var result = match ? match[1] : null;
console.log(result); // "227-84"
If there is a match, the .match()
method returns an array. In this case it would return:
["region/227-84/all", "227-84"] // match
The first capturing group has an index of one (i.e., match ? match[1] : null
). In this case, the ternary operator is simply used to check if there was actually a match before accessing the array (otherwise an error would be thrown if there wasn't a match).
Upvotes: 1