Skip to main content
 首页 » 编程设计

c#之用于识别网址的正则表达式

2024年01月21日33bonelee

我想为URL创建一个正则表达式,以便从输入字符串中获取所有链接。
正则表达式应识别URL地址的以下格式:


http(s)://www.webpage.com
http(s)://webpage.com
www.webpage.com


还有更复杂的网址,例如:
 -http://www.google.pl/#sclient=psy&hl=pl&site=&source=hp&q=regex+url&pbx=1&oq=regex+url&aq=f&aqi=g1&aql=&gs_sm=e&gs_upl=1582l3020l0l3199l9l6l0l0l0l0l255l1104l0.2.3l5l0&bav=on.2,or.r_gc.r_pw.&fp=30a1604d4180f481&biw=1680&bih=935

我有以下一个

((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; 
            } 

请您参考如下方法:

我刚刚写了一篇有关以最常用的格式识别URL的博客文章,例如:

www.google.com
http://www.google.com
mailto:somebody@google.com
somebody@google.com
www.url-with-querystring.com/?url=has-querystring

使用的正则表达式为/((([A-Za-z]{3,9}:(?:\/\/)?)(?:[-;:&=\+\$,\w]+@)?[A-Za-z0-9.-]+|(?:www.|[-;:&=\+\$,\w]+@)[A-Za-z0-9.-]+)((?:\/[\+~%\/.\w-_]*)?\??(?:[-\+=&;%@.\w_]*)#?(?:[\w]*))?)/,但是我建议您进入http://blog.mattheworiordan.com/post/13174566389/url-regular-expression-for-links-with-or-without-the来查看完整的工作示例,以及对正则表达式的解释,以防您需要扩展或调整它。