用超链接替换所有URL

时间:2017-01-09 12:40:45

标签: asp.net regex vb.net

我有以下代码,它使用正则表达式查找给定字符串中的所有网址:

Dim regex As New Regex("(http(s)?:\/\/.)?(www\.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9@:%_\+.~#?&//=]*)", RegexOptions.IgnoreCase)

现在,我想用超链接替换所有匹配项:

For Each match As Match In mactches
    strtemp &= strtemp.Replace(match, "<a target='_blank' href='mailto:" & match & "'>" & match & "</a>")
Next

正则表达式工作正常但更换时存在问题。假设我的输入字符串如下:

www.google.com is as same as google.com and also http://google.com

代码首先将www.google.com替换为<a>,然后,当第二个匹配(google.com)出现时,它将再次替换前一个匹配。那么,实现这一目标的方法是什么?

1 个答案:

答案 0 :(得分:4)

如果您使用using System; using System.Collections.Generic; using AppName.Math; using Xamarin.Forms; using Plugin.Messaging; using AppName.Flashcards; using AppName.Science; namespace AppName { public partial class AppNameHome : ContentPage { public SchoolToolsHome() { InitializeComponent(); var name = new List<Tools> { new Tools("Internet", "web.png"), new Tools("E-Mail", "email.png"), new Tools("Math", "math.png"), new Tools("Science", "sci.png"), new Tools("Handwriting","handwriteing.png"), new Tools("FlashCards", "flashcard.png"), }; listView.ItemsSource = name; } void OnItemSelected(object sender, SelectedItemChangedEventArgs e) { var tools = e.SelectedItem as Tools; if (tools == null) { return; } ContentPage page = null; switch (tools.Name) { case "Math": page = new MathPage(); break; case "Internet": Device.OpenUri(new Uri("http://www.google.com")); page = new AppNameHome(); break; case "E-Mail": Device.OpenUri(new Uri("mailto:")); page = new AppNameHome(); break; case "FlashCards": page = new FlashCardHome(); break; case "Science": page = new ScienceHome(); break; default: page = new AppNameHome(); break; } ((ListView)sender).SelectedItem = null; page.BindingContext = tools; Navigation.PushAsync(page); } public void OpenBooks(object sender, EventArgs e) { switch (Device.OS) { case TargetPlatform.iOS: Device.OpenUri(new Uri("itms-books:")); break; case TargetPlatform.Android: DependencyService.Get<OpenBookInterface>().openBooks(); break; } } public void gotosettings(object sender, EventArgs e) { Navigation.PushAsync(new SettingsPage()); } } } ,它将正常工作,因为它会在找到它们时替换每个匹配项,而不是同时替换所有其他匹配项:

Regex.Replace

但是,如果您每次调用它时只是重新创建Dim pattern As String = "(http(s)?:\/\/.)?(www\.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9@:%_\+.~#?&//=]*)" Dim regex As New Regex(pattern, RegexOptions.IgnoreCase) Dim input As String = "www.google.com is as same as google.com and also http://google.com" Dim output As String = regex.Replace(input, "<a target='_blank' href='mailto:$&'>$&</a>") 对象,则可以改为使用静态Regex方法。

Regex.Replace是一个特殊的替换表达式,它指示$&方法在替换字符串中的该点插入整个匹配。有关其他替换表达式,请参阅MSDN quick reference页面上的部分。