RegularExpression无法正常工作c#

问题描述 投票:1回答:2

我希望在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- ./?])?$

请提前建议并提前致谢!

c# regex visual-studio
2个回答
1
投票

你可以使用这个正则表达式:

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

3
投票

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

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

所以\/\/字面上匹配//,而\.匹配点。

我还添加了一些非捕获组(?:)。如果您想获得各个部分,只需省略这两个字符即可。

查看regex101

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

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

Uri uriResult;
bool result = Uri.TryCreate(myString, UriKind.Absolute, out uriResult) 
    && uriResult.Scheme == Uri.UriSchemeHttp;
© www.soinside.com 2019 - 2024. All rights reserved.