Search code examples
powershellregex-greedy

Powershell regex to get string between string and char


I have file with some variables in it like this:

${variable}

And i want to loop through file and output:

variable
variable1
variable2
variable3

etc.

My code:

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"

EXAMPLE of input file line:

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

Can anybody give me a hint?

Thanks


Solution

  • I would do it like this:

    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
    }
    

    and call te function:

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

    Because the function now takes care of escaping the strings give in $firstString and $secondString, you don't have to bother about this when calling the function. Also, because there may be more matches in the input file, the function now returns an array of matches.

    i.e. if your input file contains stuff like this:

    <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;"/>
    

    the returned matches will be

    input.cardType
    input.otherType