regular expression validator in vb.net/asp.net custom expressions - asp.net

I want to make sure using the custom expression validator that no ' or " can be used i tryed using [^"'] but whenever i put normal letters it doesnt work either.

I would just do a regex replace to match ['"] and replace it with nothing (ie. "").
In VB.NET, the code would look like:
dim strTest as string = "This "is" a test'"
dim regex as regex = new regex("[" & chr(34) & "']", regexoptions.ingorePatternWhitespace)
msgbox(regex.Replace(strTest, ""))
The output will be This is a test.

Related

Change all href tags to lower case

I have a string that contains multiple href tags such as:
href="HTTPS://www.example.com" and href="hTtp://www.example.com"
I need to change it to lower case, example:
href="https://www.example.com" and href="http://www.example.com"
what do I need to do with the code below to achieve it:
Dim strRegex As String = "<?href\s*=\s*[""'].+?[""'][^>]*?"
Dim myRegex As New Regex(strRegex, RegexOptions.IgnoreCase)
For Each myMatch As Match In myRegex.Matches(StringThatContainsHrefTags)
If myMatch.Success Then
Dim pattern As String
pattern = "http(s)?://([\w+?\.\w+])+([a-zA-Z0-9\~\!\#\#\$\%\^\&\*\(\)_\-\=\+\\\/\?\.\:\;\'\,]*)?"
If Regex.IsMatch(myMatch.ToString(), pattern) Then
'what do I do here?
End If
End If
Next
You can do it like this if you do not want to parse the HTML content.
Dim Input As String = "something asdf and then asdf"
Dim Output As String = Regex.Replace(Input, "<a\s+[^>]*href=""(?<Protocol>https?):", New MatchEvaluator(Function(X) X.Value.ToLower), RegexOptions.IgnoreCase)
This will handle only the HTTP/HTTPS part. You can extend the regex to entire URL and perform other validations from your code if needed.
There's shortcut in the code expecting only one pair of braces in the regex. Otherwise some tunning in X.Groups("Protocol").Value would be needed.

Replace all URLs with hyperlinks

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?
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.

String.Replace not replacing vbCrlf

I am trying to replace all the occurrences of "\n" in the Text property of an ASP.NET TextBox with <br /> using String.Repalce function, but it doesn't seem to work:
taEmailText.Text.Replace("\n", "<br />")
As a solution I am using Regex.Replace:
New Regex("\n").Replace(taEmailText.Text, "<br />")
My question is why String.Replace can't find "\n" for me, even though this solution has been proposed on many sites and it has worked for many people.
Thanks,
In .NET string objects are immutable, so String.Replace returns a new string with the replacement. You need to assign the result:
taEmailText.Text = taEmailText.Text.Replace("\n", "<br />")
Also, rather than creating a new Regex object—when you do need a regular expression—then there are static methods available:
result = Regex.Replace(input, pattern, replacement)
Edit (based on comment):
Just tested this:
Sub Main()
Dim result As String = "One\nTwo".Replace("\n", "<br />")
Console.WriteLine(result)
End Sub
and the result is:
One<br />Two
The problem is the result of the method call is immediated forgotten. You should read MSDN documentation a bit more carefully:
Returns a new string in which all occurrences…
Hence do:
taEmailText.Text = taEmailText.Text.Replace("\n", "<br />")
Replace does not change the content of the input string. It returns newly created string.
You might want to replace both \r and \n or use Environment.NewLine constant.
var replacedText = TextBox1.Text.Replace(Environment.NewLine, "<br />");

Concept needed for building consistent urls (routes)

My project has the need to build consistent urls similar to the ones here on stackoverflow. I know how I "can" do it by running the string through multiple filters, but I'm wondering if I can do it all with a single method.
Basically I want to remove all special characters, and replace them with dashes BUT if there are multiple dashes in a row, I need them to be a single dash. How can I implement this as clean as possible?
Example: If I were to use the following string.
My #1 Event
My regex would create the following string
my--1-event
notice how there are two dashes (one for the space and one for the "#" symbol). What I need is
my-1-event
Here's how I'm implementing it currently
''# <System.Runtime.CompilerServices.Extension()>
Public Function ToUrlFriendlyString(ByVal input As String) As String
Dim reg As New Regex("[^A-Za-z0-9]")
''# I could run a loop filter here to match "--" and replace it with "-"
''# but that seems like more overhead than necessary.
Return (reg.Replace(Trim(input), "-"))
End Function
And then all I do is call the extension method
Dim UrlFriendlyString = MyTile.ToUrlFriendlyString
Thanks in advance.
Add a + to the end of the regex.
This will tell it to match one or more characters that match the character class that precedes the +.
Also, you should create your Regex instance in a Shared field outside the method so that .Net won't need to parse the regex again every time you call the method.
[edited by rockinthesixstring]: here's the final result
Private UrlRegex As Regex = New Regex("[^a-z0-9]+", RegexOptions.IgnoreCase)
<System.Runtime.CompilerServices.Extension()>
Public Function ToUrlFriendlyString(ByVal input As String) As String
Return (UrlRegex.Replace(Trim(input), "-"))
End Function
Another way I do this without using a regex and also is a little simpler to understand is the following:
Excuse me on my vb as I am mainly C# guy.
''# <System.Runtime.CompilerServices.Extension()>
Public Function ToUrlFriendlyString(ByVal input As String) As String
If [String].IsNullOrEmpty(s) = True Then
Return [String].Empty
End If
Dim builder As New StringBuilder()
Dim slug = input.Trim().ToLowerInvariant()
For Each c As Char in slug
Select Case c
Case ' '
builder.Append("-")
Case '&'
builder.Append("and")
Case Else
If (c >= '0' And c <= '9') OrElse (c >= 'a' And c <= 'z') And c != '-')
builder.Append(c)
End If
End Select
Next
Return builder.ToString()
End Function

VB Script split issue

I use the split function of in VBScript to split the string. Below is the code am using.
Dim inputText
DIM resultArray
inputText = "abc; def; ""xyz;123"""
resultArray = Split(inputText, "; ")
For i = 0 To UBound(resultArray)
resultArray(i) = Replace(resultArray(i), """", "")
resultArray(i) = Replace(resultArray(i), ";", "")
IF i = UBound(resultArray) THEN
Response.Write resultArray(i)
ELSE
Response.Write resultArray(i) & "; "
END IF
Next
If i remove the space after ; in split function it will also split "xyz:123" which i don't want to be.
Either i gave space after ; in split function (Line # 4) or not it shouldn't split the "xyz:123" which comes in double quotes.
Any suggestion how i can achieve this ?
Thanks in advance.
That suspiciously looks like a csv-file. You could try using ADO for this. Microsoft has a fairly extensive (and very useful) article on this: http://msdn.microsoft.com/en-us/library/ms974559.aspx
Since they describe exactly your problem, I think that just might be your solution. :)

Resources