【问题标题】:PowerShell: Output of Regular Expression instead of ResultPowerShell:输出正则表达式而不是结果
【发布时间】:2012-02-13 22:30:07
【问题描述】:

好的,长期访客,第一次发帖。

而不是 PowerShell 告诉我正则表达式的结果是“真”或“假”,而是我想要字符串。我知道还有其他方法可以做到这一点,而且我已经有了一个工作版本,但我想使用正则表达式来“提取”字符串。

例如:

$ipconfig = ipconfig | select-string "IPv4" | select-object -first 1
$ipconfig -match "\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b"

只返回“True”,而不是我想要的 IP 地址。

有没有办法使用正则表达式来完成这个?

谢谢!

【问题讨论】:

    标签: regex string powershell extract


    【解决方案1】:

    你已经得到了,只需要检查一个你免费获得的变量:

    $ipconfig = ipconfig | select-string "IPv4" | select-object -first 1
    if ($ipconfig -match "\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b") { 
        $matches[0]
    }
    

    或者,您可以使用 .NET 对象:

    $ipconfig = ipconfig | select-string "IPv4" | select-object -first 1
    ([regex]"\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b").matches($ipconfig) | % { $_.value }
    

    享受:)

    【讨论】:

      【解决方案2】:

      使用-替换:

       $ipconfig = ipconfig | select-string "IPv4" | select-object -first 1 
       $ipconfig -replace '.*\b(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})\b.*','$1' 
      

      【讨论】:

        猜你喜欢
        • 2017-03-26
        • 1970-01-01
        • 2017-11-22
        • 2016-11-10
        • 2022-12-03
        • 2018-07-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多