gpt4 book ai didi

regex - 如何使用正则表达式排除目录?

转载 作者:行者123 更新时间:2023-12-01 01:20:02 25 4
gpt4 key购买 nike

不久前我问了一个关于使用正则表达式从特定目录中的 URL 中提取匹配项的问题。

例如:www.domain.com/shop/widgets/match/
给出的解决方案是^/shop.*/([^/]+)/?$
这将返回 "match"
但是,我的文件结构发生了变化,我现在需要一个返回 "match" 的表达式。在除 "pages" 之外的任何目录中和 "system"
基本上我需要一个返回 "match" 的表达式对于以下情况:

www.domain.com/shop/widgets/match/
www.domain.com/match/

但不是:
www.domain.com/pages/widgets/match/
www.domain.com/pages/

www.domain.com/system/widgets/match/
www.domain.com/system/

我已经挣扎了好几天没有任何运气。

谢谢

最佳答案

这只是上述 Grahams 伟大答案的替代方案。 C# 中的代码(但对于正则表达式部分,这无关紧要):

void MatchDemo()
{
var reg = new Regex("( " +
" (\\w+[.]) " +
" | " +
" (\\w+[/])+ " +
") " +
"(shop[/]|\\w+[/]) " + //the URL-string must contain the sequence "shop"
"(match) " ,
RegexOptions.IgnorePatternWhitespace);

var url = @"www.domain.com/shop/widgets/match/";

var retVal = reg.Match(url).Groups[5]; //do we have anything in the fifth parentheses?

Console.WriteLine(retVal);
Console.ReadLine();
}
/汉斯

关于regex - 如何使用正则表达式排除目录?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9961836/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com