Search code examples
regexpowershelltokenexpandable

How do I pass a RegEx token to a PowerShell subexpression in a RegEx substitution?


I have the following code:-

'\u0026' -replace '(\u)(\d{4})', '$$([char]0x$2)'

That will obviously result with:-

$([char]0x0026)

If I make the RegEx substitution into an expandable string with:-

'\u0026' -replace '(\\u)(\d{4})', "$([char]0x`${2})"

Then I will get:-

Unexpected token '0x`$' in expression or statement.

If I simplify things to:-

'\u0026' -replace '(\\u)(\d{4})', "0x`${2}"

Then I can get:-

0x0026

But, what I want is to cast that '0x0026' to a char so it replaces '\u0026' to '&'. However, it seems impossible to pass a RegEx substituted token to a PowerShell subexpression in this way. If you separate the two languages with:-

'\u0026' -replace '(\\u)(\d{4})', "$([char]0x0026) 0x`${2}"

Then the below will result:-

& 0x0026

Which is great as it shows PowerShell subexpressions do work in RegEx substitutions as the converted ampersand shows.

I am new to RegEx. Have I hit my limit already?


Solution

  • Apperently, you want to unescape an escaped regular expression. You can do this using the .net [regex] unescape method:

    [Regex]::Unescape('Jack\u0026Jill')
    

    Yields:

    Jack&Jill