首页 > 解决方案 > 使用正则表达式在引号内查找字符串

问题描述

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

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$./!.*+]     

无显示

标签: regexpowershell

解决方案


在您的模式中,有一些错误 escaping\u\s一个额外的空间。

您可以使用和使用捕获组重复字符类1 次以上+

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

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

正则表达式演示| Powershell 演示

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

("[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"

推荐阅读