$source |% {
switch -regex ($_){
'\<'+$primaryKey+'\>(.+)\</'+$primaryKey+'\>' {
$primaryKeyValue = $matches[1]; continue; }
}
I want to use dynamic key value with switch-regex, is that possible?
$source |% {
switch -regex ($_){
'\<'+$primaryKey+'\>(.+)\</'+$primaryKey+'\>' {
$primaryKeyValue = $matches[1]; continue; }
}
I want to use dynamic key value with switch-regex, is that possible?
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
.