Let's consider a simple one-regex approach.
Since your string is inside the query string, you might want to watch out for argument boundaries (&
and initial ?
) and use [&?]
at the pattern start. Right now, .*
will match everything even if you have more than 1 argument. In order to make sure you match groups separated with -
but not overmatch after &
, you can use a negated character class [^&-]
Next thing to consider is the optional part --<NUMBER>
. You need to group the characters and apply a ?
quantifier to that group to make it "optional" one time (?
means match 1 or 0 times). To make our match result cleaner, it is advisable to use non-capturing groups.
So, the regex will look like:
[&?]tags=([^&-]*(?:-[^&-]+)*)(?:--(\d+))?
^ | Main || ^Grp2^|
Start | capture || |
boundary | group || Optional |
See regex demo (\n
is added since this is a multiline demo).
JS:
var re = /[&?]tgs=([^&\n-]*(?:-[^&\n-]+)*)(?:--(\d+))?/;
var str = 'http://localhost:30001/catalog/search?tags=bed-green-big-33-22-ancient-5--2';
var m = str.match(re);
if (m !== null) {
document.getElementById("r").innerHTML = "First part: <b>" + m[1] + "</b><br/>Second part: <b>" + m[2] + "</b>";
}
<div id="r"/>