1
$source |% {
switch -regex ($_){
'\<'+$primaryKey+'\>(.+)\</'+$primaryKey+'\>' { 
$primaryKeyValue = $matches[1]; continue; }

}

I want to use dynamic key value with switch-regex, is that possible?

1 Answer 1

1

You can use a string which automatically expands variables:

switch -regex (...) {
    "<$primaryKey>(.+)</$primaryKey>" { ... }
}

instead of piecing everything together with string concatenation (which is rather ugly). switch -RegEx expects a literal string. Furthermore, there is no need to escape < and > in a regular expression, as those aren't metacharacters.

If you desperately need an expression which generates a string (such as your string concatenation, for whichever reason), then you can put parentheses around it:

switch -regex (...) {
    ('<'+$primaryKey+'>(.+)</'+$primaryKey+'>') { ... }
    ('<{0}>(.+)</{0}>' -f $primaryKey) { ... } # thanks, stej :-)
}

You can also use expressions that explicitly do a regex match with braces; see help about_Switch.

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

3 Comments

In this case I would use ('<{0}>(.+)</{0}>' -f $primaryKey) instead of concatenating strings.
@stej: Thanks, that's also a nice variant; I added it in :-)
@stej: I consider the inlined variables more readable in this case ... but my stance on code readability changes from time to time too :-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.