Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Escaping Closing Braces

Tags:

c#

regex

System.Text.RegularExpressions.Regex.Escape() escapes only opening braces. Is there a .NET Framework method which escapes closing braces for usage in regex? I can't seem to find any. I'd hate to hardcode the characters.

edit: I need to generate "(?<-open>)" tags for balancing group definitions. I receive a list of characters representing closing delimiters, escape them and then add them to the expression in "(?<-open>)" tags. So, yes, I really do have to escape closing braces as well.

like image 698
dijxtra Avatar asked Nov 23 '11 10:11

dijxtra


2 Answers

As said in the comment above, the behavior of the Escape function is as follows (MSDN):

Escapes a minimal set of characters (\, *, +, ?, |, {, [, (,), ^, $,., #, and white space) by replacing them with their escape codes. This instructs the regular expression engine to interpret these characters literally rather than as metacharacters.

The following remark is added:

While the Escape method escapes the straight opening bracket ([) and opening brace ({) characters, it does not escape their corresponding closing characters (] and }). In most cases, escaping these is not necessary. If a closing bracket or brace is not preceded by its corresponding opening character, the regular expression engine interprets it literally. If an opening braket or brace is interpreted as a metacharacter, the regular expression engine interprets the first corresponding closing character as a metacharacter. If this is not the desired behavior, the closing bracket or brace should be escaped by explicitly prepending the backslash () character. For an illustration, see the Example section.

Thus if the interpreter finds a } that is not preceded by an opening { it will automagically escape it.

like image 135
Timothée Bourguignon Avatar answered Sep 18 '22 15:09

Timothée Bourguignon


Regex.Escape does escape both when I try it. Is there something else going on in your code ? Posting a reproducible example of both your escaping code and regex would be helpful. I think Tim's comment is probably on the mark about what's going on too.

FWIW, testing Regex.Escape() gives these results:

Regex.Escape("(Hello)"); // \(Hello\)
Regex.Escape("Hello)"); // Hello\)
Regex.Escape("(Hello"); // \(Hello

Edit: OK from the comments I understand you meant { now, and testing with that gives the results you're saying. Regex.Escape() is trying to helpful by only escaping when need be, but if that's not what you want here there's not any other built-in method that will work. I think you'll have to 1) add the escaping it's missing in yourself, or 2) if possible, format your input string differently so that Regex.Escape will work as expected.

like image 35
Michael Low Avatar answered Sep 19 '22 15:09

Michael Low