How to use Regex Replace to conditionally remove blocks of text?
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开发者_如何学C, "")
End If
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
- Regular expressions and escaping special characters
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
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.
精彩评论