Search code examples
regexreplacepowershell-3.0powershell-4.0

$() is removed from string


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>

Solution

  • 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)