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

}

我想在 switch-regex 中使用动态键值,这可能吗?

4

1 回答 1

1

您可以使用自动扩展变量的字符串:

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

而不是将所有内容与字符串连接拼凑在一起(这很丑陋)。switch -RegEx需要一个文字字符串。此外,没有必要在正则表达式中转义<>因为它们不是元字符。

如果您迫切需要一个生成字符串的表达式(例如您的字符串连接,无论出于何种原因),那么您可以在它周围加上括号:

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

您还可以使用显式地使用大括号进行正则表达式匹配的表达式;见help about_Switch

于 2010-03-27T11:12:27.790 回答