【问题标题】:How do I filter part of a string using regex?如何使用正则表达式过滤字符串的一部分?
【发布时间】:2017-01-15 12:07:39
【问题描述】:

使用 PowerShell 我可以从包含所需文本的文件中获取行:

Get-ChildItem -recurse -Attributes !Directory+!System | Get-Content | Select-String "tshtml"

结果如下:

 templateUrl: '/tshtml/generic/gkeyvalue/gkeyvalue.html'
 templateUrl: '/tshtml/generic/permission/permission.html'
 templateUrl: '/tshtml/generic/permission2/permission2.html'

但现在我想要其中的一部分作为输出:

 /generic/gkeyvalue/gkeyvalue.html
 /generic/permission/permission.html
 /generic/permission2/permission2.html

我该怎么做?我正在阅读有关正则表达式的信息,但我对此了解不多:(

【问题讨论】:

    标签: regex powershell powershell-4.0


    【解决方案1】:
    ... | Select-String "tshtml" | ForEach { $_.Line -replace "^.*(?=/generic)|'$" }
    

    替换指向/generic 的行的开头和行尾的',什么都不做。

    Select-String "tshtml" | ForEach { if ($_.Line -match "'/tshtml(.*)'") { $Matches[1] } }
    

    捕获''之间的文本并输出。

    【讨论】:

    • 更简单的部分选项:...|Get-Content|?{$_ -match "'/tshtml(.*)'"}|%{ $Matches[1]} 不需要Select-String 然后匹配,只需一次完成。
    • @TheMadTechnician 是的。或者使用 select-string 一次性完成所有操作 ... | Select-String "'/tshtml(.*)'" | ForEach {$_.matches[0].groups[1].Value}
    【解决方案2】:

    试试下面的:

    ... | Select-String "tshtml"|awk '{print $2}'| tr -d "'"
    

    【讨论】:

    • 假设你有一个 Windows 版本的 awktr 要使用,转换为纯字符串的 Select-String 的输出也包括文件名,所以这需要是 {print $3}得到正确的输出。
    • 我知道我可以使用 sed/awk 轻松做到这一点,但不知道如何在 windows 上做到这一点:(而且我没有 sed/awk/tr 的 windows 版本
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-10-13
    • 1970-01-01
    • 2020-09-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-08
    相关资源
    最近更新 更多