regex - 在 PowerShell 中用环境变量替换正则表达式 token

标签 regex powershell replace environment-variables template-engine

与 PowerShell 发生了一些争执。我正在尝试用环境变量的值替换文本文件中的标记。例如,假设我的输入文件如下所示:

Hello [ENV(USERNAME)], your computer name is [ENV(COMPUTERNAME)]
and runs [ENV(OS)]

我试过以下方法:

Get-Content test.txt | ForEach {$_ -replace '\[ENV\((\w+)\)\]', "$env:$1" }

这给出了错误:

At line:1 char:74
+ Get-Content test.txt | ForEach {$_ -replace '\[ENV\((\w+)\)\]', "$env:$1 ...
+                                                                  ~~~~~
Variable reference is not valid. ':' was not followed by a valid variable name character. Consider using ${} to delimit the name.
    + CategoryInfo          : ParserError: (:) [], ParentContainsErrorRecordException
    + FullyQualifiedErrorId : InvalidVariableReferenceWithDrive

我也试过:

Get-Content test.txt | ForEach {$_ -replace '\[ENV\((\w+)\)\]', [environment]::GetEnvironmentVariable($1) }

但这无法检索变量并将其作为输出给我:

Hello , your computer is named
and runs

我试图调用我自己定义的函数,但出现另一个错误:

At D:\tfs\HIPv3\prod\Dev\Tools\EnvironmentResolve.ps1:13 char:72
+ Get-Content test.txt | ForEach {$_ -replace '\[ENV\((\w+)\)\]', GetEnvVa ...
+                                                                 ~~~~~~~~
Missing expression after ','.
At D:\tfs\HIPv3\prod\Dev\Tools\EnvironmentResolve.ps1:13 char:73
+ Get-Content test.txt | ForEach {$_ -replace '\[ENV\((\w+)\)\]', GetEnvVa ...
+                                                                 ~~~~~~~~
Unexpected token 'GetEnvVar' in expression or statement.
    + CategoryInfo          : ParserError: (:) [], ParseException
    + FullyQualifiedErrorId : MissingExpressionAfterToken

有人知道怎么做吗?

最佳答案

我明白了:

$string = 'Hello [ENV(USERNAME)], your computer name is [ENV(COMPUTERNAME)] and runs [ENV(OS)]'

$regex = '\[ENV\(([^)]+)\)]'

 [regex]::Matches($string,$regex) |
  foreach {
            $org = $_.groups[0].value
            $repl = iex ('$env:' + $_.groups[1].value)
            $string = $string.replace($org,$repl)
          }

 $string

关于regex - 在 PowerShell 中用环境变量替换正则表达式 token ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14793973/

相关文章:

php - 正则表达式在线替换组后的所有空格

powershell - 解决 PowerShell 的“"You don' t 当前有权访问此文件夹”问题

powershell - 变量替换 - 引用不起作用

windows - git add commit Push one 适用于 powershell windows

javascript - 向字符串化 JSON 对象值添加引号

regex - 如何在 perl 替换中转义 REPLACEMENT?

mysql - 请使用正确的正则表达式语法提供建议

python - 使用正则表达式从字符串中提取子字符串

c++ - regex_search 返回 true,但 regex_match 返回空匹配集

python - 如何在 python 中将文本文件分段?