tags:

views:

69

answers:

2

I would like to conditionally remove a block of text between specifed start and stop delimiters. The code below does not work, but hopefully it suggests enough of what I am trying to accomplish.

            If dr("ReferralPoints") > 0 Then
                Dim objRegex As Regex = New Regex("[HASNOVALUE:REFERRALPOINTS](.*)[/HASNOVALUE:REFERRALPOINTS]", RegexOptions.IgnoreCase + RegexOptions.Singleline)
                Dim result As String = objRegex.Replace(strBody, "")
            End If
+3  A: 

The regular expression needs to be the following:

\[HASNOVALUE:REFERRALPOINTS](.*)\[/HASNOVALUE:REFERRALPOINTS]

You need to escape [ here because it's a regex metacharacter.

In VB.NET, (based on this quick reference sheet), it looks like \ is not an escape character, so you can simply write this as:

"\[HASNOVALUE:REFERRALPOINTS](.*)\[/HASNOVALUE:REFERRALPOINTS]"

See also


Also, in case you don't know, (.*) is greedy, and will take the longest match. You may need (.*?) instead, but this really depends on the problem definition.

---AxxZ----AxxZ----
   ^^^^^^^^^^^^
      A(.*)Z
polygenelubricants
+1 for the nice visual on greedy (.*). :-)
Platinum Azure
A: 

Do you need to escape the square brackets? In many other regex languages, square brackets create a character class, meaning that the engine needs only find one of the characters within the brackets to call it a match.

If you escape the brackets, probably with a backslash '\', that might be enough. I'll be the first to admit I'm not sure about ASP.NET specifically, though.

Platinum Azure
Ack, it might be two as per polygenelubricants' answer.
Platinum Azure
@Platinum: I'll be second to admit I have no idea how ASP.NET does it either =)
polygenelubricants
I believe it's only one backslash in vb.
xpda