Reputation: 12319
The following Regex pattern in PowerShell is giving me real trouble. The double and single quotes are the culprits but I don't know how to get PowerShell to accept it. How do I get PowerShell to successfully accept this pattern?
If I copy the pattern to a variable PowerShell complains about an unexpected token after the first quote found within the pattern.
$myRegex = "^param[\s?]*\([\$\sa-zA-Z\=\@\(\)\"\d\,\:\\\_\.\']*\)"
I then attempted to escape the double quote by adding another quote next to it. This time the string is accepted but the regex fails. Notice the double double quote in the next example.
$myRegex = "^param[\s?]*\([\$\sa-zA-Z\=\@\(\)\""\d\,\:\\\_\.\']*\)"
$somelongString -replace $myRegex
Error Message:
The regular expression pattern ^param[\s?]*\([\$\sa-zA-Z\=\@\(\)\"\d\,\:\\\_\.\']*\) is not valid.
Update 1: Per @Dan Farrell's suggestion I updated my regex as follows:
$myRegex = "^param(\s?)*\([\$\sa-zA-Z\=\@\(\)\""\d\,\:\\\_\.\']*\)"
Update 2: This is a working example of my Regex which I am trying to port to PowerShell
Upvotes: 1
Views: 222
Reputation: 627087
Escaping _
in a .NET regex causes an error. To use a "
inside "..."
string literal, you need to escape it with a backtick, use `"
. Besides, you only need to escape \
inside your character class.
Use
$myRegex = "^param\s*\([$\sa-zA-Z=@()`"\d,:\\_.']*\)"
Upvotes: 1