C# 使用正则表达式获取字符串中的链接
我需要检查字符串是否包含链接并打印它。到目前为止,这是我的代码C# 使用正则表达式获取字符串中的链接,c#,regex,C#,Regex,我需要检查字符串是否包含链接并打印它。到目前为止,这是我的代码 string strRegex = @"(http://\w+\.\w+\.\w+)"; Regex myRegex = new Regex(strRegex, RegexOptions.None); string strTargetString = @"An http://w.facebook.me http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd ahttp vhttp b... ../
string strRegex = @"(http://\w+\.\w+\.\w+)";
Regex myRegex = new Regex(strRegex, RegexOptions.None);
string strTargetString = @"An http://w.facebook.me http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd ahttp vhttp b... ../ .. extraordinary day dawns with each new day.";
foreach (Match myMatch in myRegex.Matches(strTargetString))
{
if (myMatch.Success)
{
Console.WriteLine(myMatch.Value);
}
}
输出:
http://w.facebook.me
http://www.w3.org
输出应该是
http://w.facebook.me
http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd
在我的正则表达式中,我不想再添加一个\w+
,因为我不知道链接中会有多少斜杠和多长单词
那么我怎样才能做得更好呢?在不知道链接的长度的情况下,如何获取链接
谢谢将正则表达式更改为
"(http://\w+\.\w+\.\w+(\/\w+)*)"
如果你想匹配链接,比如在末尾加一个斜杠,只需将其改为
"(http://\w+\.\w+\.\w+(\/\w+)*\/?)"
将正则表达式更改为
"(http://\w+\.\w+\.\w+(\/\w+)*)"
如果你想匹配链接,比如在末尾加一个斜杠,只需将其改为
"(http://\w+\.\w+\.\w+(\/\w+)*\/?)"
regex only return我需要完整的链接regex only return我需要完整的链接