PowerShell可以替换使用-clike找到的文本中区分大小写的部分吗?

假设我有两个地址:

  • 纽瓦克路 123 号
  • 荷兰大道 987 号

我需要将方向部分从 Ne 更新到 NE。但是,我不想将纽瓦克更新为 NEwark,而对于荷兰也是如此。我想我可以在循环中使用这个 IF 语句轻松找到所有实例:

$testAddress = '123 Newark Road Ne'
if (($testAddress -clike '* Ne') -or ($testAddress -clike '* Ne *')){
   #code to replace Ne
}

But how do I go about replacing it? I can't use a -creplace '* Ne', '* NE'. Finding the index of '* Ne' just gives me -1 so I don't think I can do anything with that. I'm sure there's an easy concept that I'm just not coming across.

回答

您可以使用正则表达式将输入的某个部分替换为在正则表达式中的替换操作数中无法通过设计(如 .NET 中的大写)通过使用 a 来替换输入的某个部分MatchEvaluator,它在 PowerShell 中像脚本块一样构造。

使用 MatchEvaluator,您可以随意操作匹配的部分,因此在操作方面您不受任何限制。

从 PowerShell 6 开始,您甚至可以直接与-replace-creplace运算符一起使用它。
低于 6 的 PowerShell 版本没有此选项,但仍然可以使用 .NET Regex Replace Method[regex]::Replace()和 MatchEvaluator。

PS 5.1

$textToReplace = 'Ne 123 Newark Road Ne', '123 Newark Road Ne', '987 Ne Netherland Avenue'

foreach ($text in $textToReplace) {
    # using a scriptblock as System.Text.RegularExpressions.MatchEvaluator
    # the param() part is mandatory. Everything that follows is the return for that particular match
    [regex]::Replace($text, '(?<!w)Ne(?!w)', { param($regexMatch) $regexMatch.Value.ToUpper() })
}
$textToReplace = 'Ne 123 Newark Road Ne', '123 Newark Road Ne', '987 Ne Netherland Avenue'

foreach ($text in $textToReplace) {
    # using a scriptblock as System.Text.RegularExpressions.MatchEvaluator
    # the param() part is mandatory. Everything that follows is the return for that particular match
    [regex]::Replace($text, '(?<!w)Ne(?!w)', { param($regexMatch) $regexMatch.Value.ToUpper() })
}

PS 6+

正则表达式模式说明

该模式使用and组结构(?<!w)Ne(?!w)匹配Ne其前后字符不是单词字符的所有单词。negative lookbehind (?<!)negative lookahead (?!)

w(Word) in.NET包括以下类别的所有Unicode字符:
MSFT:正则表达式中的字符类 -> Word 字符:w:

这些包括但不限于:

  • a-z 和变体,如 è
  • A-Z 和变体,如 À
  • 0-9
  • _
  • 西里尔字符
  • 中国文字
  • ...

简而言之,它w捕获了几乎所有以 Unicode 字符集表示的单词字符。

资源

MSFT:用 PS6+ 中的脚本块替换


以上是PowerShell可以替换使用-clike找到的文本中区分大小写的部分吗?的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>