1

Let's say I have a string:

$line = "name=""abc"""

I want to extract whatever is written within the quotation marks, like this:

 [regex]::Matches($line,'(?<=name=").+?(?=")').Value

This works, but I want the word "name" to be passed as a variable to the regex, i.e. I have a variable $identifyer="name" and I want this to work:

 [regex]::Matches($line,'(?<=$identifiyer=").+?(?=")').Value

but it does not work.

3
  • In short: In PowerShell, only "..." strings (double-quoted aka expandable strings) perform string interpolation (expansion of variable values and expressions), not also '...' strings (single-quoted aka verbatim strings). With "..." quoting, if the string value itself contains " chars., escape them as `" or "", or use a double-quoted here-string. See the linked duplicate and the conceptual about_Quoting_Rules help topic. Commented Sep 22 at 11:32
  • As an aside: a perhaps more PowerShell-idiomatic solution is $line -replace "$identifier=`"(.+)`"", '$1'. If you want to rule out false positives and match the line in full: $line -replace "^$identifier=`"(.+)`"`$", '$1' Commented Sep 22 at 12:01
  • If the source is actually a PowerShell data file/string, you better use the PowerShell (AST) parser for this. Commented Sep 23 at 7:27

2 Answers 2

3

It doesn't work because of quoting.

String between single quotes ' are treated as literals. $identifiyer included.

You'd need to use double quotes " in the regex to have $identifiyer being recognized as variable, but that can be messy.

Luckily it's not the only way to insert values of variables inside strings: String Formatting to the rescue!

$line = 'name="abc"'

$identifier = 'name'

$RegexString = '(?<={0}=").+?(?=")' -f $identifier

[regex]::Matches($line, $RegexString).Value

Much easier to the eye

Sign up to request clarification or add additional context in comments.

Comments

2

In my opinion this can be handled more easily by not using regex, but simple string operations. Take a look at below function:

function Get-ValueFromLine {
    param(
        [string]$Line,
        [string]$Key
    )

    # Split into key and value
    $parts = $Line -split '=', 2
    if ($parts.Count -ne 2) {
        return $null
    }

    # Trim all double quotes
    $lineKey = $parts[0].Trim()
    $val = $parts[1].Trim('"')

    return $lineKey -eq $Key ? $val : $null
}

Usage

Get-ValueFromLine 'name="abc"' 'name'

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.