C# 带有URL提取的正则表达式

C# 带有URL提取的正则表达式,c#,.net,regex,url,C#,.net,Regex,Url,我在这个项目中使用C#,基本上我需要的是一种将纯文本转换为HTML的方法,我发现了一个正则表达式(我认为实际上是堆栈溢出),用于将文本中的链接转换为HTML中的锚定链接,它看起来像这样: Regex regx = new Regex(@"https?://([-\w\.]+)+(:\d+)?(/([\w/_\.]*(\?\S+)?)?)?", RegexOptions.IgnoreCase); MatchCollection mactches = regx.Ma

我在这个项目中使用C#,基本上我需要的是一种将纯文本转换为HTML的方法,我发现了一个正则表达式(我认为实际上是堆栈溢出),用于将文本中的链接转换为HTML中的锚定链接,它看起来像这样:

        Regex regx = new Regex(@"https?://([-\w\.]+)+(:\d+)?(/([\w/_\.]*(\?\S+)?)?)?", RegexOptions.IgnoreCase);

        MatchCollection mactches = regx.Matches(input);
        foreach (Match match in mactches)
        {
            output = output.Replace(match.Value, String.Format("<a href=\"{0}\" target=\"_blank\">{0}</a>", match.Value));
        }
Regex regx=new Regex(@“https:/([-\w\.]+)+(:\d+)(/([\w/\.]*(\?\S+)?),RegexOptions.IgnoreCase);
MatchCollection mactches=regx.Matches(输入);
foreach(麦琪牌)
{
output=output.Replace(match.Value,String.Format(“,match.Value));
}

它工作得很好,但是我发现了一个缺陷,即它不把一个破折号(-)当作URL的一部分,所以当它碰到第一个破折号时,它就关闭了锚标签。 所以我显然需要在正则表达式中包含破折号,但问题是我对正则表达式一无所知,它看起来就像俄语。 有人知道我需要对正则表达式进行多小的编辑才能使其在URL中包含破折号作为允许的字符吗?

试试这个:
@“https:/([-\w\.]+)+(:\d+)(/([-\w/\u\.]*(\?\ S+)?“


我在第二个字符类(方括号中的部分)中添加了一个破折号,以匹配URL中非域名部分的破折号。

我使用这个破折号,它支持
ftp
文件
方案以及
http

@"\b((https?|ftp|file)://|(www|ftp)\.)[-A-Z0-9+&@#/%?=~_|$!:,.;\(\)]*[A-Z0-9+&@#/%=~_|$]"
它将识别包含由
&
分隔的参数的URL,如下所示:

        Regex regx = new Regex(@"https?://([-\w\.]+)+(:\d+)?(/([\w/_\.]*(\?\S+)?)?)?", RegexOptions.IgnoreCase);

        MatchCollection mactches = regx.Matches(input);
        foreach (Match match in mactches)
        {
            output = output.Replace(match.Value, String.Format("<a href=\"{0}\" target=\"_blank\">{0}</a>", match.Value));
        }

原文在。我对其进行了轻微修改,以识别包含以下括号的URL:

        Regex regx = new Regex(@"https?://([-\w\.]+)+(:\d+)?(/([\w/_\.]*(\?\S+)?)?)?", RegexOptions.IgnoreCase);

        MatchCollection mactches = regx.Matches(input);
        foreach (Match match in mactches)
        {
            output = output.Replace(match.Value, String.Format("<a href=\"{0}\" target=\"_blank\">{0}</a>", match.Value));
        }


您需要指定
RegexOptions.IgnoreCase
使用此正则表达式,当然您可以通过将
A-Z
替换为
\w

来简化。您能给出一个它不匹配的URL的示例吗?我的测试表明它是……而且,您的
匹配项拼写错误:p+1。就这么简单。我没有意识到OP在目录上有问题。太棒了!非常感谢你把它修好了。问题在于“漂亮”SEO链接中带有破折号的URL,例如: