首页 > 解决方案 > Powershell:当正则表达式替换发现不匹配时抑制输出

问题描述

默认情况下,即使没有进行替换,powershell“-replace [regex]”也会生成输出。
我怎样才能抑制这个输出,因为这将使它在使用超过 4000 个名称作为输入的同时具有大量重复和额外数据的大小

示例脚本:

"allal","farid","widad"|%{
     $name=$_;"a","i","e","o","y","u"|%{
        ([Regex]"($_)").Replace($name,"`$1`$1",1)  }
}

输出:

aallal
allal     #must not exist in output
allal     #must not exist in output
allal     #must not exist in output
allal     #must not exist in output
allal     #must not exist in output
faarid
fariid
farid     #must not exist in output
farid     #must not exist in output
farid     #must not exist in output
farid     #must not exist in output
widaad
wiidad
widad     #must not exist in output
widad     #must not exist in output
widad     #must not exist in output
widad     #must not exist in output

想要的方法:当没有匹配存在时抑制输出。
以下低效和不需要的方法:

$output|sls "aa|ii|ee|oo|yy|uu"

标签: regexpowershell

解决方案


如果与Regex.Replace方法匹配或不匹配,则无法返回信息。您只能在正则表达式替换之前和之后比较字符串。

我建议[aeuioy]直接在Regex.Replace方法中使用模式来替换所有出现:

 "allal","farid","widad"|%{
>>      ([Regex]"[aoueiy]").Replace($_,"`$&`$&")
>> }
aallaal
faariid
wiidaad

使用 Powershell 7,您可以使用

PS> "allal","farid","widad"|%{
>>      $name=$_;"a","i","e","o","y","u"|%{
>>         $name.Contains($_) ? ([Regex]"$_").Replace($name,'$&$&', 1) : ''  }
>> } | Where-Object { $_ }
aallal
faarid
fariid
widaad
wiidad

在这里,$name.Contains($_)确保the中有一个元音$name(所以,肯定会有一个匹配),如果是,Regex.Replace则运行,否则返回一个空字符串,随后Where-Object { $_ }删除那些空字符串。


推荐阅读