字符串替换在powershell中不起作用

Posted

技术标签:

【中文标题】字符串替换在powershell中不起作用【英文标题】:string replace doesn't work in powershell 【发布时间】:2019-05-23 06:29:54 【问题描述】:

我在使用 powershell 时遇到了问题。 这是我的代码:

$content = [IO.File]::ReadAllText(".\file.js")
$vars = @()

ForEach ($line in $($content -split "`r`n")) 
    if ($line -Match "=") 
        $vars += $line.substring(0,$line.IndexOf("="))
    
    ForEach ($e in $vars) 
        $line = $line.Replace($e, "$" + $e)
    
    Write-Host($line)

而file.js是:

x = 123
(x)

此代码的输出是 $x = 123 和 (x)。 (x) 应该是 ($x)。线$line = $line.Replace($e, "$" + $e) 不工作。

编辑: 好的。问题是 $e 等于 "x ",而不是 "x"

【问题讨论】:

【参考方案1】:

您已经找到了解决自己问题的关键,您意识到您尝试从x = 123 这样的行中提取x 是有缺陷的,因为它提取了(带有尾随空格)。

最简单的解决方法是从子字符串提取语句的结果中删除空格(注意.Trim() 调用):

# Extract everything before "=", then trim whitespace.
$vars += $line.substring(0,$line.IndexOf("=")).Trim()

但是,请考虑按如下方式精简您的代码:

$varsRegex = $sep = ''

# Use Get-Content to read the file as an *array of lines*.
Get-Content .\file.js | ForEach-Object 

  # See if the line contains a variable assignment.
  # Construct the regex so that the variable name is captured via 
  # a capture group, (\w+), excluding the surrounding whitespace (\s).
  if ($_ -match '^\s*(\w+)\s*=') 
    # Extract the variable name from the automatic $Matches variable.
    # [1] represents the 1st (and here only) capture group.
    $varName = $Matches[1]
    # Build a list of variable names as a regex with alternation (|) and
    # enclose each name in \b...\b to minimize false positives while replacing.
    $varsRegex += $sep + '\b' + $varName + '\b'
    $sep = '|'
  

  # Replace the variable names with themselves prefixed with '$'
  # Note how '$' must be escaped as '$$', because it has special meaning in 
  # the replacement operand; for instance, '$&' refers to what the regex
  # matched in the input string (in this case: a variable name).
  $line = $_ -replace $varsRegex, '$$$&'

  # Output the modified line.
  # Note: Use Write-Host only for printing directly to the screen.
  $line


【讨论】:

以上是关于字符串替换在powershell中不起作用的主要内容,如果未能解决你的问题,请参考以下文章

字符串在我的函数中不起作用作为参数powershell [重复]

字符串连接在 SQLite 中不起作用

排序在Powershell函数中不起作用[重复]

sqldataadapter 在 powershell 中不起作用

如果循环在powershell函数中不起作用[关闭]

访问更新语句在 C# 中不起作用