如何在 PowerShell 中使用正则表达式替换

时间:2021-01-16 21:02:37

标签: regex powershell replace

ipconfig | Select-String "IPv4 Address" 返回如下内容:

   IPv4 Address. . . . . . . . . . . : 192.168.1.50
   IPv4 Address. . . . . . . . . . . : 172.20.112.1
   IPv4 Address. . . . . . . . . . . : 192.168.208.1

假设我想使用 -replace 用空字符串替换“IPv4 地址......我该怎么做?这是我尝试过的:

ipconfig | Select-String "IPv4 Address" -replace "IPv4 Address. . .",""

这给了我以下错误:

Select-String : A parameter cannot be found that matches parameter name 'replace'.
At line:1 char:41
+ ipconfig | Select-String "IPv4 Address" -replace "IPv4 Address. . .", ...
+                                         ~~~~~~~~
    + CategoryInfo          : InvalidArgument: (:) [Select-String], ParameterBindingException
    + FullyQualifiedErrorId : NamedParameterNotFound,Microsoft.PowerShell.Commands.SelectStringCommand

有什么想法吗?

3 个答案:

答案 0 :(得分:1)

你可以使用

ipconfig | Select-String "IPv4 Address" | foreach { $_ -replace '.*:\s*' }

使用 .*:\s*,您可以匹配一行中最后一个 : 之前的所有文本,\s* 还会消耗冒号之后的零个或多个空白字符。

这是regex demo

答案 1 :(得分:1)

仅使用 Select-String,您可以使用捕获组来提取 IP 地址:

ipconfig | Select-String "IPv4 Address.*:\s*(.+)" | ForEach-Object { $_.Matches.Groups[1].Value }
  • .*: 匹配直到 :
  • 的所有内容
  • \s* 匹配 : 和 IP 地址之间的任何(零个或多个)空格
  • (.+) 匹配 IP 地址(多一个字符)并在组 1 中捕获它
  • $_.Matches.Groups[1].Value 输出捕获组 1 的值,即 IP 地址

This link 很好地概述了在 PowerShell 中使用 RegEx 的多种可能性。

答案 2 :(得分:-3)

安装 Git。启动 Git Bash 并使用 grepsed(或 cutawk):

$ ipconfig | grep 'IPv4 Address' | sed 's/.*: //'

s/xyz/abc/ 表示sxyz替换abc

相关问题