代码之家  ›  专栏  ›  技术社区  ›  One Developer

PowerShell中的switch-regex

  •  1
  • One Developer  · 技术社区  · 15 年前
    $source |% {
    switch -regex ($_){
    '\<'+$primaryKey+'\>(.+)\</'+$primaryKey+'\>' { 
    $primaryKeyValue = $matches[1]; continue; }
    
    }
    

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

    1 回复  |  直到 15 年前
        1
  •  1
  •   Joey Gumbo    15 年前

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

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

    而不是把所有的东西都用字符串连接起来(这很难看)。 switch -RegEx 需要文本字符串。而且,没有必要逃跑 < > 在正则表达式中,因为它们不是元字符。

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

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

    还可以使用表达式显式地与大括号进行regex匹配;请参见 help about_Switch .