Reputation: 705
I have following code which uses regex to find all the urls within a given string:
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)
Now, I want to replace all the matches with hyperlinks:
For Each match As Match In mactches
strtemp &= strtemp.Replace(match, "<a target='_blank' href='mailto:" & match & "'>" & match & "</a>")
Next
The regex works fine but there is an issue while replacing. Suppose my input string is as follows:
www.google.com is as same as google.com and also http://google.com
The code will first replace www.google.com
with <a>
and then, when the second match (google.com
) comes up, it will again replace the previous one. So, what is a way of achieving this?
Upvotes: 2
Views: 523
Reputation: 43743
If you use Regex.Replace
, it will work correctly, since it will replace each occurrence as it finds them rather than replacing all other matches at the same time:
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>")
However, if you are just going to recreate the Regex
object each time you call it, you could just use the static Regex.Replace
method instead.
The $&
is a special substitution expression which instructs the Replace
method to insert the entire match at that point in the replacement string. For other substitution expressions, see the section on the MSDN quick reference page.
Upvotes: 4