【问题标题】:Perl Regex to not match a repeated patternPerl 正则表达式不匹配重复的模式
【发布时间】:2014-03-21 20:58:42
【问题描述】:

我正在尝试确定我在 cisco 路由器上放置的命令是否在以下输出中只有邻居条目..

我有以下正则表达式 .. 如果搜索到末尾并且找不到第二个匹配项,如何让搜索失败?

if (! $document =~/(Device\sID)(.*?)(Device\sID)/s){        
    print("Theres no double entries\n");
} else { 
    print ("double!\n");
}

Device ID: NAME1
Entry address(es): 
  IP address: IP.IP.IP.IP
Plautform: cisco WS-C3850-48T,  Capabilities: Switch IGMP 
Interface: GigabitEthernet1/x,  Port ID (outgoing port): GigabitEthernetx/x/x
Holdtime : 123 sec

Version :
Cisco IOS Software, IOS-XE Software, Catalyst L3 Switch Software (CAT3K_CAA-UNIVERSALK9-M), Version 03.02.03.SE RELEASE SOFTWARE (fc2)
Technical Support: http://www.cisco.com/techsupport
Copyright (c) 1986-2013 by Cisco Systems, Inc.
Compiled Mon 23-Sep-13 18:24 by prod_rel_team

advertisement version: 2
VTP Management Domain: 'NAME1'
Native VLAN: 1
Duplex: full
Management address(es): 
  IP address: IP.IP.IP.IP

问候, 彼得

【问题讨论】:

  • 嘿彼得,重读你的问题的第一句话,也许重做它? "...在以下输出中只有邻居条目.." 你能举一个例子,说明某处是双精度,而某处没有双精度吗?如果您试图查看是否有重复的设备 ID,那么最简单的解决方案就是将它们全部拉出,然后查找重复项。但就目前的情况而言,对于给定的数据和问题,您的目标是什么尚不清楚。
  • 嗨。你能提供一个测试条件和一个输出吗?另外我认为从if 中去掉! 并交换ifelse 的主体会更好。我不明白搜索失败的意思。

标签: regex perl cisco


【解决方案1】:

您遇到了运算符优先级的问题。 ! 的优先级高于 =~,所以你的表达式:

 if ( ! $document =~ /(Device\sID)(.*?)(Device\sID)/s ) {

是一样的:

 if ( (! $document) =~ /(Device\sID)(.*?)(Device\sID)/s ) {

但你想要:

 if ( ! ($document =~ /(Device\sID)(.*?)(Device\sID)/s) ) {

就是这样:

 if ( $document !~ /(Device\sID)(.*?)(Device\sID)/s ) {

【讨论】:

  • 感谢您的逻辑分解。像冠军一样工作!
【解决方案2】:

!~ 是正则表达式不匹配的运算符。

$document !~ /(Device\sID)(.*?)(Device\sID)/s

【讨论】:

  • Yes 比 "match" if else 好得多
  • 这可能是一个有用的提醒,但它与问题无关,不提供答案。
  • @Borodin 不,这就是答案。在 =~ 的 if 条件中使用 ! 是错误的。 OP 想要How do I get the search to fail if it reaches the end and doesn't find the second match,这与我的回答相符。
  • 我非常感谢您提供的帮助。从一位工程师到另一位工程师!
猜你喜欢
  • 2011-08-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多