简体   繁体   中英

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, "")
            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


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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM