$() is removed from string

Viewed 25

I want to replace old validation with the new validation. But the new validation regex is removing $() from Regex.

$oldValidation="<RegexPattern>^[\da-zA-Z\s+()\-']+$</RegexPattern>"
$newValidation= "<RegexPattern>^[\w\s,.;+&'""!?$()@%]*$</RegexPattern>"
$_.Fields["Parameters"].value -replace $oldValidation, $newValidation   

But the newValidation is removing $() from regex and showing it like this

<RegexPattern>^[\w\s,.;+&'"!?@%]*$</RegexPattern>
2 Answers

This can help:

$oldValidation="<RegexPattern>^[\da-zA-Z\s+()\-']+$</RegexPattern>"
$newValidation= "<RegexPattern>^[\w\s,.;+&'""!?`$()@%]*$</RegexPattern>"
$_.Fields["Parameters"].value -replace [regex]::escape($oldValidation), $newValidation.Replace('$','$$')

Please check there is a backtick before $.

Another possible solution is using .Replace after backtick is used in $newValidation:

$_.Fields["Parameters"].value.Replace($oldValidation, $newValidation)

According to https://regex101.com, $ means end of line in regex. () is used for capture groups. You would have to backslash them to use them literally.

Related