【发布时间】:2011-08-18 12:49:59
【问题描述】:
我想为 url 创建一个正则表达式,以便从输入字符串中获取所有链接。 正则表达式应能识别以下格式的 url 地址:
- http(s)://www.webpage.com
- http(s)://webpage.com
- www.webpage.com
我有以下一个
((www\.|https?|ftp|gopher|telnet|file|notes|ms-help):((//)|(\\\\))+[\w\d:#@%/;$()~_?\+-=\\\.&]*)
但它无法识别以下模式:www.webpage.com。有人可以帮我创建一个合适的正则表达式吗?
编辑: 它应该可以找到合适的链接,并将链接放在合适的索引中,如下所示:
private readonly Regex RE_URL = new Regex(@"((https?|ftp|gopher|telnet|file|notes|ms-help):((//)|(\\\\))+[\w\d:#@%/;$()~_?\+-=\\\.&]*)", RegexOptions.Multiline);
foreach (Match match in (RE_URL.Matches(new_text)))
{
// Copy raw string from the last position up to the match
if (match.Index != last_pos)
{
var raw_text = new_text.Substring(last_pos, match.Index - last_pos);
text_block.Inlines.Add(new Run(raw_text));
}
// Create a hyperlink for the match
var link = new Hyperlink(new Run(match.Value))
{
NavigateUri = new Uri(match.Value)
};
link.Click += OnUrlClick;
text_block.Inlines.Add(link);
// Update the last matched position
last_pos = match.Index + match.Length;
}
【问题讨论】: