我有以下字符串
/search?checkin=2018-10-25&checkout=2018-10-27&id=bandung-108001534490276290&page=1&room=1&sort=popularity&type=CITY
/search?checkin=2018-12-09&checkout=2018-12-13&id=singapore-108001534490299035&maxPrice=&minPrice=&room=1&type=REGION
/search?checkin=2018-10-22&checkout=2018-10-23&lat=-6.1176043&long=106.7767146&maxPrice=&minPrice=&room=1&type=COORDINATE
/search?page=1&room=1&type=POI&id=taman-mini-indonesia-indah-110001539700828313&checkin=2018-11-14&checkout=2018-11-16&sort=distance
我想让所有字符串从&id=
开始直到第一个&
,以便它们返回
id=bandung-108001534490276290
id=singapore-108001534490299035
id=taman-mini-indonesia-indah-110001539700828313
当我尝试使用此正则表达式\&id=.*\&
时,它不符合我的要求。
我能解决这个问题吗?
答案 0 :(得分:1)
我会和[?&](id=[^&]+)
一起去。
[?&]
-?
或&
,因为通常无法保证GET参数的顺序,因此您可以首先获取ID,例如/search?id=something-123456&checkin=2018-10-25&…
[^&]+
-至少一个不是&
的字符()
标记了一个捕获组在JS中演示:
const strings = [
"/search?checkin=2018-10-25&checkout=2018-10-27&id=bandung-108001534490276290&page=1&room=1&sort=popularity&type=CITY",
"/search?checkin=2018-12-09&checkout=2018-12-13&id=singapore-108001534490299035&maxPrice=&minPrice=&room=1&type=REGION",
"/search?checkin=2018-10-22&checkout=2018-10-23&lat=-6.1176043&long=106.7767146&maxPrice=&minPrice=&room=1&type=COORDINATE",
"/search?page=1&room=1&type=POI&id=taman-mini-indonesia-indah-110001539700828313&checkin=2018-11-14&checkout=2018-11-16&sort=distance]"
]
const regex = /[?&](id=[^&]+)/
strings.forEach(string => {
const match = regex.exec(string)
if (match) {
console.log(match[1])
}
})
Regex101上的演示和说明:https://regex101.com/r/FBeNDN/1/
答案 1 :(得分:0)
(?=)
尝试积极的前瞻:
/&id=.+?(?=&)|&id=.+?$/gm
此部分:(?=&)
的意思是:如果找到了&
,那么它之前的所有内容都是匹配的。
交替:|
(这是OR
逻辑门)是对Nick的评论的更新,该评论涉及参数是否以&id=...
结尾
这是相同的匹配项,但不是寻找&
,而是寻找行$
的结尾。请注意,m
最后一行标志用于使$
代表EOL。
var str = `/search?checkin=2018-10-25&checkout=2018-10-27&id=bandung-108001534490276290&page=1&room=1&sort=popularity&type=CITY
/search?checkin=2018-12-09&checkout=2018-12-13&id=singapore-108001534490299035&maxPrice=&minPrice=&room=1&type=REGION
/search?page=1&room=1&type=POI&id=indo-1999999051158
/search?checkin=2018-10-22&checkout=2018-10-23&lat=-6.1176043&long=106.7767146&maxPrice=&minPrice=&room=1&type=COORDINATE
/search?page=1&room=1&type=POI&id=taman-mini-indonesia-indah-110001539700828313&checkin=2018-11-14&checkout=2018-11-16&sort=distance
/search?page=1&room=1&type=POI&id=indonesia-1100055689`;
var rgx = /&id=.+?(?=&$)|&id=.+?$/gm;
var res = rgx.exec(str);
while (res != null) {
console.log(res[0]);
res = rgx.exec(str);
}