Powershell正则表达式在字符串和字符之间获取字符串

时间:2018-10-26 07:17:53

标签: powershell regex-greedy

我的文件中包含一些这样的变量:

${variable}

我想遍历文件和输出:

variable
variable1
variable2
variable3

我的代码:

function GetStringBetweenTwoStrings($firstString, $secondString, $importPath){

    #Get content from file
    $file = Get-Content $importPath

    #Regex pattern to compare two strings
    $pattern = "$firstString(.*?)$secondString"

    #Perform the opperation
    $result = [regex]::Match($file,$pattern).Groups[1].Value

    #Return result
    return $result

}

GetStringBetweenTwoStrings -firstString "\\${" -secondString "}" -importPath ".\start.template"

输入文件行的示例:

<input id="paymentMethod_VISA" type="radio" name="${input.cardType}" value="VISA" checked="checked" style="width: 1.5em; height: 1.5em;"/>

有人可以给我一个提示吗?

谢谢

2 个答案:

答案 0 :(得分:3)

我会这样:

function GetStringBetweenTwoStrings($firstString, $secondString, $importPath){
    #Get content from file
    $file = Get-Content $importPath -Raw

    #Regex pattern to compare two strings
    $regex = [regex] $('{0}(.*?){1}' -f [Regex]::Escape($firstString), [Regex]::Escape($secondString))

    $result = @()
    #Perform and return the result
    $match = $regex.Match($file)
    while ($match.Success) {
        $result += $match.Groups[1].Value
        $match = $match.NextMatch()
    }
    return $result
}

并调用te函数:

GetStringBetweenTwoStrings -firstString '${' -secondString '}' -importPath '<PATH_TO_YOUR_INPUT_FILE>'

由于该函数现在可以避免转义$firstString$secondString中给出的字符串,因此在调用该函数时不必为此而烦恼。 另外,由于输入文件中可能存在更多匹配项,因此该函数现在返回匹配项数组。

即如果您的输入文件包含以下内容:

<input id="paymentMethod_VISA" type="radio" name="${input.cardType}" value="VISA" checked="checked" style="width: 1.5em; height: 1.5em;"/>
<input id="paymentMethod_OTHER" type="radio" name="${input.otherType}" value="Other" checked="checked" style="width: 1.5em; height: 1.5em;"/>

返回的匹配项将是

input.cardType
input.otherType

答案 1 :(得分:1)

我提供了@Theo建议的替代实现:

脚本:

$path = ".\file.txt"
$content = Get-Content -Path $path -Raw
$m = $content | Select-String -pattern '\${(?<variable>[^}]+)}' -AllMatches
$m.matches.groups | Where-Object {$_.Name -eq "variable"} | ForEach-Object {Write-Output $_.Value}

输入文件:

<input id="paymentMethod_VISA" type="radio" name="${input.cardType}" value="VISA" checked="checked" style="width: 1.5em; height: 1.5em;"/> <input id="${input.second}" type="${input.third};"/>

输出:

input.cardType
input.second
input.third