【问题标题】:Powershell - matching a string which might contain whitespacePowershell - 匹配可能包含空格的字符串
【发布时间】:2017-04-16 14:47:32
【问题描述】:

使用 Powershell 版本 3 并读取文件的内容,然后我需要查看文件中是否包含多个字符串之一,如果存在则替换它们。就我而言,问题是我需要匹配的其中一个字符串中可能包含可变数量的空格(或根本没有空格)。

我要匹配的字符串中有双引号,后跟一个冒号 (:),然后是空格(或无),然后是任意数量的状态(可以是字母或数字),后跟一个逗号。为简单起见,我只是在下面的代码中使用了一个数字。

$txt = (Get-Content $file)
$oldstr = "`"status`": 1,"
$newstr = '`"status`": 0,"
if (($txt.Contains($old1)) -or ($txt.Contains($oldstr)) -or ($txt.Contains($old2))) {
    $txt.Replace($oldstr, $newstr).Replace($old1, $new1).replace($old2, $new2)| Set-Content -Path $file
}

我遇到的问题是匹配$oldstr,它可能没有,冒号和状态代码之间有一个或多个空格,在本例中是一个数字,但也可能是几个不同的数字或字符串。 $newstr 不需要从 $oldstr 复制空格。此外,在上面的示例中,它使用了 Contains 中的三个条件之一。实际数据可能不包含、一个、两个或所有三个字符串。

如何匹配/包含和替换其中可以包含空格的字符串?

【问题讨论】:

  • 好吧,你需要正则表达式来做到这一点;)但我无法帮助你;)

标签: string powershell replace contains


【解决方案1】:

Here is an interessant solution 具有多个匹配/替换对,并将哈希表转换为组合正则表达式。但是我没有在哈希键中加入正则表达式,所以我对 foreach 中的 $_ 做了表和正则表达式。

# Build hashtable of search and replace values.

$file = ".\testfile.txt"

$replacements = @{
  'something2' = 'somethingelse2'
  'something3' = 'somethingelse3'
  'morethings' = 'morethingelses'
  'blabla'    = 'blubbblubb'
}
# Join all keys from the hashtable into one regular expression.
[regex]$r = @($replacements.Keys | foreach { [regex]::Escape( $_ ) }) -join '|'

[scriptblock]$matchEval = { param( [Text.RegularExpressions.Match]$matchInfo )
  # Return replacement value for each matched value.
  $matchedValue = $matchInfo.Groups[0].Value
  $replacements[$matchedValue]
}
$fileCont = Get-Content $file
# Perform replace over every line in the file and append to log.
$Newfile = $fileCont | ForEach { 
  $r.Replace( ( $_ -replace '"status":\s*0','"status": 1'), $matchEval ) 
} 

$fileCont
"----"
$Newfile

在我的 testfile.txt 中给出这个输出

> .\Replace-Array.ps1
"Status":  0, something2,morethings
"Status":    0, something3, blabla
----
"status": 1, somethingelse2,morethingelses
"status": 1, somethingelse3, blubbblubb

【讨论】:

    【解决方案2】:

    使用带有-replace 运算符的正则表达式:

    PS C:\> '"status":      0' -replace '"status":\s*0','"status": 1'
    "status": 1
    PS C:\> '"status": 0' -replace '"status":\s*0','"status": 1'
    "status": 1
    PS C:\> '"status":0' -replace '"status":\s*0','"status": 1'
    "status": 1
    

    在我上面使用的模式中:

    • "status": 只匹配文字字符串 "status":
    • \s* 匹配 0 个或多个空白字符
    • 0 匹配文字 0

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-06-02
      • 1970-01-01
      • 1970-01-01
      • 2016-02-26
      • 2019-04-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多