开发者

Switch -Regex in Powershell

开发者 https://www.devze.com 2022-12-24 03:12 出处:网络
$source |% { switch -regex ($_){ \'\\<\'+$prim开发者_如何学JAVAaryKey+\'\\>(.+)\\</\'+$primaryKey+\'\\>\' {
$source |% {
switch -regex ($_){
'\<'+$prim开发者_如何学JAVAaryKey+'\>(.+)\</'+$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.

0

精彩评论

暂无评论...
验证码 换一张
取 消