我需要解析 url /domain.com?filter[a.b.c]=value1&filter[a.b.d]=value2
并得到 2 个组:'a.b.c' 和 'a.b.d'。
我尝试使用正则表达式 [\?&]filter\[(.+\..+)+\]=
进行解析,但结果是 'a.b.c]=value1&filter[a.b.d '。如何指定搜索第一次出现?
最佳答案
你可以使用
/[?&]filter\[([^\].]+\.[^\]]+)]=/g
参见 regex demo
详情
[?&]
-?
或&
filter\[
-filter[
子串([^\].]+\.[^\]]+)
- 捕获第 1 组:[^\].]+
- 除了]
和之外的 1 个或多个字符。
\.
- 一个点[^\]]+
-]
以外的 1 个或多个字符
]=
-]=
子串
JS 演示:
var s = '/domain.com?filter[a.b.c]=value1&filter[a.b.d]=value2';
var rx = /[?&]filter\[([^\].]+\.[^\]]+)]=/g;
var m, res=[];
while(m=rx.exec(s)) {
res.push(m[1]);
}
console.log(res);
请注意,如果 &
永远不会作为查询参数值的一部分出现,您可以将其添加到否定字符类中,[^\].]+
=> [^\]&.]+
,以确保正则表达式不会在参数值之间过度匹配。
由于您需要提取外方括号内的文本,这些方括号可能包含连续的 [...]
子字符串,其中一个子字符串中至少有 1 个点,因此您可以使用更简单的正则表达式代码:
var strs = ['/domain.com?filter[a.b.c]=value1&filter[a.b.d]=value2',
'/domain.com?filter[a.b.c]=value1&filter[a.b.d]=value2&filter[a][b.e]=value3',
'/domain.com?filter[a.b.c]=value1&filter[b][a.b.d][d]=value2&filter[a][b.e]=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 ----");
}
关于javascript - 使用正则表达式解析查询参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50679890/