正则表达式网站上只有一个子文件夹,

时间:2018-06-18 19:51:56

标签: c# regex url

任何人都可以帮助正确的正则表达式模式吗? 基本上我想捕获所有只有一个子文件夹的字符串,之后没有别的东西(除了正斜杠)。

这是我的正则表达式,但它与所有内容都不匹配:

Regex Pattern: http(s)?:\/\/(.*).(.*)/(\w-)*\b

匹配的字符串(我想要匹配的是箭头):

    http://test.org/
==> http://test.org/SubFolder1             
    http://test.org/SubFolder1?Query=Test
    http://test.org/SubFolder1/SubFolder2
    http://test.org/SubFolder1/SubFolder2?Query=Test
    http://www.test.org/
==> http://www.test.org/SubFolder1  
    http://www.test.org/SubFolder1?Query=Test
    http://www.org/SubFolder1/SubFolder2
    http://www.org/SubFolder1/SubFolder2?Query=Test
    www.test.org/
==> www.test.org/SubFolder1  
    www.test.org/SubFolder1?Query=Test
    www.org/SubFolder1/SubFolder2
    www.org/SubFolder1/SubFolder2?Query=Test

提前致谢。

2 个答案:

答案 0 :(得分:1)

使用regexr我能够解决问题。很多时候,您无法使用google确切的解决方案,因此您应该花一些时间来了解如何根据自己的独特需求编写正则表达式。

(https?:\/\/)?\w+\.+[\w\.]*\/[\w-]+$
  • 可选https
  • 一个或多个字母
  • 1个或更多点
  • 任意数量的字母或点
  • 斜线(我在这里逃过一劫,你没有逃脱 - 有时需要它)
  • 一个或多个字母或连字符(你的连字符是你的)
  • 行尾

我创建了一个regexr here,它以非常图形的方式解释了解决方案。

答案 1 :(得分:1)

而不是正则表达式,只需使用内置的UriUriBuilder类:

首先创建一个方法来确定输入字符串是否匹配:

public static bool IsMatch(string url)
{
    Uri uri = new UriBuilder(url).Uri;
    return uri.Segments.Length == 2 && string.IsNullOrWhiteSpace(uri.Query);
}

然后你可以使用LINQ过滤你的列表:

var matchedUrls = urls.Where(IsMatch);

小提琴here

相关问题