Regex - Replace Text Inside Angle Brackets

JumpyNET

Centurion
Joined
Apr 4, 2005
Messages
196
How can I replace text inside angle brackets?

My best try so far:
Code:
        Dim Input As String = "Aaaa [abc] Bbbb [7] Ccc"
        Dim Output As String = Regex.Replace(Input, "\[.+\]\s", "")
        ' Output is "Aaaa Ccc" but should be "Aaaa Bbbb Ccc"
 
This is an issue of greedy versus lazy quantifiers. Basically, a greedy quantifier, such as *, will try to match as much as possible. Your regex describes a string with brackets on either end, which does match the string "[abc] Bbbb [7]". You want the lazy version, which will find the smallest match possible.

Check out http://www.regular-expressions.info/reference.html
*? (lazy star) Repeats the previous item zero or more times. Lazy, so the engine first attempts to skip the previous item, before trying permutations with ever increasing matches of the preceding item.
 
Back
Top