【问题标题】:Find a string within a quotation mark with regular expression使用正则表达式在引号内查找字符串
【发布时间】:2020-01-11 11:48:54
【问题描述】:

我想在网络交换机配置行中找到一个用引号括起来的密码,但没有成功。有人可以帮忙吗?例如:我在配置中有一行:

set snmp v3 usm local-engine user Admin authentication-sha authentication-key "$aBCd./!Test" 

我写了一个这样的正则表达式,但它不起作用。

^set\s\snmp\sv3\s\usm\slocal-engine\suser\sAdmin\sAuthentication-sha\sauthentication-key\s[0-9A-Za-z$./!.*+]     

^set\s\snmp\sv3\s\usm\slocal-engine\suser\sAdmin\sAuthentication-sha\sauthentication-key\s[0-9A-Za-z$./!.*+]     

什么都不显示

【问题讨论】:

    标签: regex powershell


    【解决方案1】:

    这将匹配双引号之间的任何内容,但它假定只有一个这样的对。捕获的组在$Matches自动变量@索引1中。

    $InStuff = 'set snmp v3 usm local-engine user Admin authentication-sha authentication-key "$aBCd./!Test"'
    
    $Null = $InStuff -match '.+"(.+)"'
    
    $Matches[1]
    

    输出 = $aBCd./!Test

    【讨论】:

      【解决方案2】:

      在您的模式中,转义 \u\s 和一个额外的空格有一些错误。

      您可以使用+ 重复character class 1+ 次并使用捕获组

      要同时匹配Authentication,您可以使匹配不区分大小写,使用大写字符或使用[aA] 来匹配两者。

      ^set\ssnmp\sv3\susm\slocal-engine\suser\sAdmin\sAuthentication-sha\sauthentication-key\s"([0-9A-Za-z$./!.*+]+)"
      

      Regex demo | Powershell demo

      如果双引号应该是结果的一部分,您可以将它们添加到捕获组。

      ("[0-9A-Za-z$./!.*+]+")
      

      例如

      $Str = 'set snmp v3 usm local-engine user Admin authentication-sha authentication-key "$aBCd./!Test" '
      $Pattern = '^set\ssnmp\sv3\susm\slocal-engine\suser\sAdmin\sAuthentication-sha\sauthentication-key\s("[0-9A-Za-z$./!.*+]+")'
      $match = $Str -match $Pattern
      $Matches[1] # First capturing group
      

      输出

      "$aBCd./!Test"
      

      【讨论】:

      • 我尝试 ("[0-9A-Za-z$./!.*+]+") 也捕获双引号,但它给了我一个错误。错误消息说“您必须在数组索引表达式之后的'-'运算符+缺少']'之后提供一个值表达式。我还尝试将双引号放在括号内,例如 (["0-9A-Za-z %./!.*+"]+ 但还是不行
      • @user12042581 我添加了一个示例脚本,如何获取包含双引号的捕获组。
      猜你喜欢
      • 1970-01-01
      • 2017-06-18
      • 2015-01-22
      • 2017-06-04
      • 1970-01-01
      • 2016-08-20
      • 1970-01-01
      • 2015-08-26
      • 1970-01-01
      相关资源
      最近更新 更多