代码之家  ›  专栏  ›  技术社区  ›  Martin Fric

Powershell regex获取字符串和字符之间的字符串

  •  0
  • Martin Fric  · 技术社区  · 6 年前

    我有一个文件,里面有一些变量,比如:

    ${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 回复  |  直到 6 年前
        1
  •  3
  •   Theo    6 年前

    我会这样做:

    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 ,调用函数时不必为此操心。 另外,因为输入文件中可能有更多匹配项,所以函数现在返回一个匹配项数组。

    i、 e.如果您的输入文件包含以下内容:

    <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
    
        2
  •  1
  •   Krzysztof Błażełek    6 年前

    我提供了@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