问题
I'm getting stuck on regex101 with the following test string:
https://localhost:8443/site/recipes/recepten-zoeken/menugang:hoofdgerecht/soort:italiaans/seizoen:winter?Nrpp=24
I'm trying to match everything in between: recepten-zoeken/ and ?
My current tries lead me nowhere as i'm very novice writing regexes. Anyone wanting to chip in?
This is what I currently have:
.(?=([^/recepten-zoeken/]?)*$)
回答1:
Use capturing group.(() brackets indicates capturing group)
Capture upto last question mark
Try this regex \/recepten-zoeken\/(.*)\?
Explanation:-
\/Match forward slashrecepten-zoekenMatch literally\/Match forward slash(.*)Capture in a group all value(except new line) upto last question mark in string(This will contain your value)\?Match literally
//-------------------------select upto last ? -----------------------------
str = "https://localhost:8443/site/recipes/recepten-zoeken/menugang:hoofdgerecht/soort:italiaans/seizoen:winter?Nrpp=24";
var myRegexp = /\/recepten-zoeken\/(.*)\?/;
console.log(myRegexp.exec(str)[1]);
Capture upto first question mark
Try this regex \/recepten-zoeken\/([^?]*)\?.
Explanation:-
\/Match forward slashrecepten-zoekenMatch literally\/Match forward slash([^?]*)Capture in a group all value(except ?) upto first question mark in string(This will contain your value)(here [^?] means match any character except?)\?Match literally
//-------------------------select upto first ? -----------------------------
var str = "https://localhost:8443/site/recipes/recepten-zoeken/menugang:hoofdgerecht/soort:italiaans/seizoen?:winter?Nrpp=24";
var myRegexp = /\/recepten-zoeken\/([^?]*)\?/;
console.log(myRegexp.exec(str)[1]);
回答2:
Try capturing your values in a capturing group:
recepten-zoeken\/([^?]+)\?
Explanation
recepten-zoekenMatch literally\/Match forward slash([^?]+)Capture in a group a negated character class[^which will match NOT a question mark. (This will contain your value)\?Match literally
var s = "https://localhost:8443/site/recipes/recepten-zoeken/menugang:hoofdgerecht/soort:italiaans/seizoen:winter?Nrpp=24"
console.log(s.match(/recepten-zoeken\/([^?]+)\?/)[1])
Credits to ctwheels for providing the snippet and comment.
回答3:
This would do it:
var match = url.match(/\/recepten-zoeken\/([^?]+)\?/);
// match[1] == "menugang:hoofdgerecht/soort:italiaans/seizoen:winter"
This regex will match the first occurrence of /recepten-zoeken/, then it will start capturing all characters that are not question marks ([^?] is a negative character class which matches anything not in the class).
Note that it will also ensure that there is a question mark. If you want to support cases where there is no question mark, then just remove the final \?.
Your original regular expression only matches a single character (the .), then it tries to look ahead for characters that are not c, e, k, / or between n and z.
来源:https://stackoverflow.com/questions/49881450/regex-that-wil-match-after-keyword-and-before-question-mark