RegularExpression无法正常工作c#

时间:2017-12-22 07:14:32

标签: c# regex visual-studio

我希望在Regular Expression -

的帮助下获得以下结果
http://articles-test.mer.com --> should not match/accept or return false

http://articles-test.mer.com/ --> should not match/accept or return false

http://articles-test. mer.com/ --> should not match/accept or return false

http://articles-test. mer.com/sites --> should not match/accept or return false

http://articles-test.mer.com/sites --> should match/accept or return true

http://foodfacts.merc.com/green-tea.html --> should match/accept or return true  

http://articles-test.merc.com/sites/abc.aspx --> should match/accept or return true  

结论 - 如果URL只有domain,则应该not match/accept

我尝试使用下面的expression,但它没有按预期工作 -

  

^ http(s)?://([\ w-] +。)+ [\ w-] +(/ [\ w- ./?])?$

请提前建议并提前致谢!

2 个答案:

答案 0 :(得分:3)

您只需要转义点,因为它通常意味着任何单个字符。这同样适用于斜线。所以你的正则表达式变成了这个:

^http(?:s)?:\/\/(?:[\w-]+\.?)+\/[\w-\.]+(\/[\w-])?$

因此\/\/字面上与//匹配,而\.与点匹配。

我还添加了一些非捕获组(?:)。如果您想要来获取各个部分,请忽略这两个字符。

查看regex101

编辑:我已在\.后面的部分添加了/,这样您也可以匹配文件而不是网址中的目录。

EDIT2:您应该明确考虑使用Uri.TryCreate检查给定字符串是否为有效网址,如this post所示,而不是使用难以理解的正则表达式重新发明轮子。

Uri uriResult;
bool result = Uri.TryCreate(myString, UriKind.Absolute, out uriResult) 
    && uriResult.Scheme == Uri.UriSchemeHttp;

答案 1 :(得分:1)

您可以使用此正则表达式:

^http(s)?://[^/\s]+/.+$
相关问题