views:

185

answers:

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

}

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

+1  A: 

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.

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