正则表达式失败

时间:2015-07-30 15:39:38

标签: c# .net regex

我正在尝试解析一串文本中的URL。目前我的RegEx模式如下所示:

(http(s)?://)?\S+\.(com|net|org|edu)\S*(?<!\W)

示例文字:

On that sample page (http://example.com/test/new.php), when you use the button, they are there, but when you use the inline, they are not.

现在它一直在捕捉开场(。我似乎无法做到这一点。有小费吗?我正在使用.NET 4.0和C#来尝试解析它。

更新:更能反映其需要捕获的链接的示例文本

On that sample page (http://example.com/test/new.php), when you use the button, it redirects to sample.com/help instead of https://www.example.com or just example.com

5 个答案:

答案 0 :(得分:3)

因为你的第一个组?之后有(http(s)?://)?,所以正则表达式引擎可以自由地回溯并尝试表达而不匹配它。因为表达式的下一部分是\S*+,所以可以自由地匹配括号和网址的其余部分。

在这种情况下,删除?应该可以解决问题,但不能解决使其成为可选问题的问题。如果该部分实际上需要是可选的并且可能提供一些额外的样本数据,请告诉我。

答案 1 :(得分:1)

如果在正则表达式前添加\b(字边界)锚点,它将按预期工作:

\b(http(s)?://)?\S+\.(com|net|org|edu)\S*(?<!\W)

答案 2 :(得分:1)

问题是\ S +比(http(s)?://)更贪婪地匹配?

你的表达有效地成为:

\S+\.(com|net|org|edu)\S*(?<!\W)

你可以通过删除&#34;?&#34;来看到这一点。来自http表达式:

(http(s)?://)\S+\.(com|net|org|edu)\S*(?<!\W)

您可能还想阅读本文,以便更多地了解问题的真正困难。

https://mathiasbynens.be/demo/url-regex

答案 3 :(得分:0)

感谢gymbrall向我展示其错误的原因,并感谢PaulF向我指出了一个带有部分答案的stackoverflow问题。我能够修改此question中的正则表达式以满足我的需求:

((http|ftp|https):\/\/)*([\w\-_]+(?:(?:\.[\w\-_]+)+))([\w\-\.,@?^=%&amp;:/~\+#]*[\w\-\@?^=%&amp;/~\+#])?(?<!\W)

使用示例文本:

On that sample page (http://example.com/test/new.php), when you use the button, it redirects to sample.com/help instead of https://www.example.com or just example.com

正则表达式将正确匹配:

http://example.com/test/new.php
sample.com/help
https://www.example.com
example.com

答案 4 :(得分:-1)

我不能100%确定为什么这不起作用,但是这个应该为你完成工作。

(http://?|https://?)\S+\.(com|net|org|edu)\S*(?<!\W)

在这里试一试:http://derekslager.com/blog/posts/2007/09/a-better-dotnet-regular-expression-tester.ashx