VB.Net - RegEx

RegEx

RegEx is a language used for string manipulation.

To me, RegEx has always been hard, but the alternatives are harder ;^).

My advise is, When you play with RegEx, do a lot of testing. Especially test strings with multiple copies of the expression you are looking for.

Replace with RegEx

1
2
3
4
5
6
imports system.text.regularexpressions

dim ps as string
ps=Regex.replace(sz, "____\r\n", "<hr>")

ps=regex.replace(sz, "\+B\+", "<B>")

Replace has 3 arguments

  • the string we want to play with
  • the characters we want to find within the string
  • the characters that will be converted

The first replace function above replaces 4 underscores (and a linefeed) with an <hr> tag.
The second replace function replaces plus B plus with a <b> tag.

The second and third arguments could contain regular expressions. Here are a few things to note.

  • The backslash character is used by the expression function.
  • \r means carriage return.
  • \n means linefeed.
  • The plus character is also used by the expression function. Since we need that we can prefix it with a \ character to indicate that’s a character we really want.

Another form of the replace function goes like this

1
2
ParsedText = Regex.Replace(ParsedText, _
"\[\[FORM.*\]\]", AddressOf aFormTag)

This will call a function called aFormTag which could resemble the following:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
Public Shared Function aFormTag(ByVal m As Match) As String
' 0 1 2
' converts [ [FORM:Missing Person|EMAIL|mark at thecoffeeplace.com]]
' into a submit button
Dim sz As String = ""

Dim tag As String = m.Value
If Left(tag, 2) = "[[" Then
tag = Mid(tag, 8, Len(tag)) ' strip off [[Form
End If
If Right(tag, 2) = "]]" Then
tag = Mid(tag, 1, Len(tag) - 2) ' strip off ]]
End If
Dim args() As String = tag.Split("|")

sz = "<input type='Hidden' name='FormType' value='" & args(1).ToUpper & "'>" & vbCrLf _
& "<input type='button' " _
& "value='" & args(0) & "' " _
& "OnClick='btnSubmitIt__Click()'>" & vbCrLf
Return sz
End Function

\d{1,3} –> 1 to 3 digits