Escape Regular Expressions

by Jul 20, 2011

PowerShell supports regular expressions in a lot of areas which is why the following code fails:

'c:\test\subfolder\file' -split '\'

Split expects a regular expression and fails when you use special characters like "\". To translate a plain text into an escaped regular expression text, try this:

[Regex]::Escape('\')
\\

As you see, "\" is the RegEx escape character and therefore needs to be escaped:

'c:\test\subfolder\file' -split '\\'
('c:\test\subfolder\file' -split '\\')[-1]

 

Twitter This Tip!
ReTweet this Tip!