regex - 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"
解决方案
如果与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 { $_ }
删除那些空字符串。
推荐阅读
- apache-edgent - 如何过滤 Apache Edgent 并显示被过滤的值?
- node.js - 如何将 Dynamo db 与 Express Angular 应用程序连接起来
- python - 我需要分组并在python中获得排名
- javascript - 新行作为空格和终止符
- angular - 为什么 keypress 在 mat-select 中不起作用?
- sql - 删除对 PIVOT 表的子查询
- c++ - c++ float* 数组作为对 std::vector 的引用
- javascript - 即使我没有在对等候选人中添加冰候选人,Webrtc 呼叫也会连接
- gitlab - 如何正确使用部署令牌
- r - 通过矢量索引访问 data.table 列?