Skip to content

Instantly share code, notes, and snippets.

@jrich523
Last active August 29, 2015 14:10
Show Gist options
  • Save jrich523/7625de86d7ea6aed9e13 to your computer and use it in GitHub Desktop.
Save jrich523/7625de86d7ea6aed9e13 to your computer and use it in GitHub Desktop.
Odd Regex Escape
#this is all powershell, but its using the .net Escape()
#i've also made it use the .net match() with similar results.
#based on the MSDN docs it looks like it doesnt need to escape a ], which makes sense if there is no open
$chars = "abcd[]."
"a","b" | %{ $_ -match "[$([regex]::Escape($chars))]"}
[regex]::Match("a","[$([regex]::Escape($chars))]").Success
#output is all false
$escchars = "abcd\[\]\."
"a","b" | %{ $_ -match "[$escchars]"}
[regex]::Match("a","[$escchars]").Success
#output is all true
http://msdn.microsoft.com/en-us/library/system.text.regularexpressions.regex.escape%28v=vs.110%29.aspx
Regex.Escape Method
"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."
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment