Regex match group to string in PowerShell

2019-07-17 01:50发布

问题:

I have a regex that does a search on a string and creates two match groups:

    if ($BASICEDITMESSAGECONTENT -match '(?sm)(^.*?</title>)(.*)')
    {
        if ($matches.Count -ge 3)
        {
            $BASICEDITMESSAGECONTENT = "$matches[1]$SCRIPTREFERENCE$matches[2]"
            echo $BASICEDITMESSAGECONTENT
            ...
        }
    }

When I echo it back, I get the following output:

System.Collections.Hashtable[1]<MYSCRIPTREFERENCE>System.Collections.Hashtable[2]

I don't want System.Collections.Hashtable values like this in the string, I just want the actual value string of the matching text from that regex grouping. How can I make it happen?

For example, when I use echo $matches[1], it displays the actual value of the regular expression group, not System.Collections.Hashtable[1].

回答1:

You need to use sub-expressions to index the hashtables:

$BASICEDITMESSAGECONTENT = "$($matches[1])$SCRIPTREFERENCE$($matches[2])"

Notice the $(...) around each index. All parts of string literals that you want evaluated as expressions need to be placed inside $(...). Otherwise, PowerShell will only expand the variable names and treat other stuff like [1] as just normal text.