I'm writing a language interpreter in PowerShell (the language is PILOT, for those who might be interested), and I've gotten to the point where I'm implementing variable replacement. A variable name consists of either a $
or a #
, followed by up to ten characters in the set [A-Za-z0-9]
. However, if the variable name is prefixed by a \
, it should not be replaced. As near as I can figure, the pattern I'm looking to match is [^\\][\$#]\w{,10}
, but I'm not clear on how to store the result of the match in a PowerShell variable so that I can look up the variable name in a table to replace it with its value.
For example, if the powershell variable $expr
contains the string \#Foo has the value #Foo
, and $vartable["#Foo"]
contains the value 5
, I would need to capture #Foo
- the second one only - in $varname, and then do a replace of the captured #Foo
with $vartable[$varname] - $expr -replace "[^\\][\$#]\w{,10}",$vartable[$varname]
should yield \#Foo has the value 5
.
Have I correctly calculated the pattern, and how do I capture the match?
(I should note that I'm developing this with PowerShell 5.1, but expect it to be able to run in that version or anything later, including PSCore on non-Windows OSes.)