首页 > 解决方案 > 如何在 Powershell 中输出正则表达式匹配中的所有字符串?

问题描述

我想在文件中搜索这个正则表达式:

<html:productType>.+?</html:productType>

如何在另一个文件中输出 .+ 的所有匹配项?上面的正则表达式?另外,您是否推荐任何其他工具/脚本语言来处理此类内容?

标签: powershell

解决方案


由于没有关于数据结构的信息,无论是 XML 还是 HTML 或其他什么,Powershell 和 Regex 就足够了。我推荐正则表达式命名组来标记重要片段。请参阅以下演示:

#prepare demo data
@'
<node>
  <html:productType>ABC</html:productType>
  <html:productType>DEF</html:productType>
</node>
'@ | Out-File Demo.txt

cat Demo.txt | Select-String '<html:productType>(?<MyGroup>.+?)<\/html:productType>' | % {
    $_.Matches[0].Groups['MyGroup'].Value
} | Out-File Demo.out

推荐阅读