I need to parse the url /domain.com?filter[abc]=value1&filter[abd]=value2
and get 2 groups: ' abc ' and ' abd '.
I try to parse with regexp [\\?&]filter\\[(.+\\..+)+\\]=
but the result is ' abc]=value1&filter[abd '. How can I specify to search for the 1st occurrence?
You may use
/[?&]filter\[([^\].]+\.[^\]]+)]=/g
See the regex demo
Details
[?&]
- a ?
or &
filter\\[
- a filter[
substring ([^\\].]+\\.[^\\]]+)
- Capturing group 1:
[^\\].]+
- 1 or more chars other than ]
and .
\\.
- a dot [^\\]]+
- 1 or more chars other than ]
]=
- a ]=
substring JS demo:
var s = '/domain.com?filter[abc]=value1&filter[abd]=value2'; var rx = /[?&]filter\\[([^\\].]+\\.[^\\]]+)]=/g; var m, res=[]; while(m=rx.exec(s)) { res.push(m[1]); } console.log(res);
Note that in case &
is never present as part of the query param value, you may add it to the negated character classes, [^\\].]+
=> [^\\]&.]+
, to make sure the regex does not overmatch across param values.
Since you need to extract text inside outer square brackets that may contain consecutive [...]
substrings with at least 1 dot inside one of them, you may use a simpler regex with a bit more code:
var strs = ['/domain.com?filter[abc]=value1&filter[abd]=value2', '/domain.com?filter[abc]=value1&filter[abd]=value2&filter[a][be]=value3', '/domain.com?filter[abc]=value1&filter[b][abd][d]=value2&filter[a][be]=value3']; var rx = /[?&]filter((?:\\[[^\\][]*])+)=/g; for (var s of strs) { var m, res=[]; console.log(s); while(m=rx.exec(s)) { if (m[1].indexOf('.') > -1) { res.push(m[1].substring(1,m[1].length-1)); } } console.log(res); console.log("--- NEXT STRING ----"); }
(?<=[\?&]filter\[)([^\]]+\.[^\]]+)+(?!>\]=)
This will give you only the groups you mentioned ( abc
and abd
)
This part (?<=[\\?&]filter\\[)
says recognise but don't capture [?&]filter
before what you want and this part (?!>\\]=)
says recognise but don't capture after ]
after what you want.
[^\\]]
this captures everything that isn't a square bracket
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.