我正在寻找一个正则表达式字符串,以便在第一个字符串结束后匹配(没有尾部斜杠或空白)
https://domain/a/ab
https://domain/a/cd/
这样我就可以在它的末尾添加一个参数,所以类似这样的东西:
https://domain/a/ab&letters=true
到目前为止,我已经想出了这个,但它只匹配字符串的最后一个字符,这不是我想要的
(?!https://domain/.*?)(.)$
如有任何帮助或建议,我们将不胜感激。
根据您的问题,我将做一些假设:
- 您有一个包含url的多行字符串
- 您希望根据路由将querystring参数附加到其中的每一个
Regex捕获每行的最后一个字符
到目前为止,您已经尝试使用正则表达式来匹配每行的最后一个字符,我认为这不会帮助您完成所需的内容。在任何情况下,当使用多行字符串时,都可以使用标志g
和m
。来自mozilla:
g
:全局匹配;查找所有匹配项,而不是在第一个匹配之后停止
m
:多行;将开头和结尾字符(^和$)视为在多行上工作(即,匹配每行的开头或结尾(由\n或\r分隔),而不仅仅是整个输入字符串的开头或末尾)
有了这些标志,像/(.)$/gm
这样简单的表达式就会捕获每行的最后一个字符。
Regex捕获每个url
根据我的假设,我认为你最好捕获URL并映射它们:
/^https?://[^/]+(/?.*)$/gm
此正则表达式每行匹配一个url,并捕获域之后的路径。
你提到你在使用javascript,所以这里有一个演示:
const regex = /^https?://[^/]+(/?.*)$/gm;
const str = `https://domain/a/ab
https://domain/a/cd/
https://domain/
http://domain
`;
let m;
while ((m = regex.exec(str)) !== null) {
// This is necessary to avoid infinite loops with zero-width matches
if (m.index === regex.lastIndex) {
regex.lastIndex++;
}
// The result can be accessed through the `m`-variable.
m.forEach((match, groupIndex) => {
console.log(`Found match, group ${groupIndex}: ${match}`);
});
}
如果您想将该文本附加到原始字符串,可以执行以下操作:
var string = "https://domain/a/abnhttps://domain/a/cd/";
string = string.replace(/^(.*)(n.*)/, "$1&letters=truen$2");
console.log(string);