An easier way to find the last balanced square bracket in a line with the .net-regex extension is to look for the line from right to left using the Regex.RightToLeft property. This way you avoid:
- to search the entire string for nothing
- to check the end of the line with lookahead, since the pattern returns the first match on the right.
code:
string input = @"[hello] [world] [hello [world\]] ]"; string rtlPattern = @"(?(c)(?!))\[(?>\\.|(?<!\\)[^][]+|(?<-c>)\[|(?<c>)])*]"; Match m; m = Regex.Match(input, rtlPattern, RegexOptions.RightToLeft); if (m.Success) Console.WriteLine("Result: {0}", m.Groups[0].Value);
demo
Please note that in order to understand what is happening, you also need to read parts of the template from right to left. Details:
]
(*) Please note that the use of an atomic group is mandatory here in order to avoid a possible catastrophic return, since the group contains an element with a quantifier + and repeats itself. You can learn more about this issue here .
This pattern already applies to escaped nested brackets, and you can also add the Regex.Singleline property if you want to combine the part containing the newline character.
source share