为什么我的正则表达式会切断这个mac地址的最后一个字符?

2024-09-27 00:21:55 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在编写一个Python脚本,它连接到Cisco IOS设备,并从特定命令收集特定信息

我正在尝试为未经身份验证的设备添加“show log”命令中列出的MAC地址。我已经尝试过在IOS命令行中直接执行命令管道输出到Regex,因为我看到多个消息源说它应该可以工作。。。但我无法让它发挥作用(对此我并不担心)

当我尝试使用Python匹配正则表达式时,它会匹配所有内容,但会切断mac地址的最后一个字符

代码:

macpattern = re.compile(r"([A-Za-z0-9]{1,4}\.[A-Za-z0-9]{1,4}\.[A-Za-z0-9]{1,4})\w+")
for line in f:
        macTest = macpattern.findall(line)
        print(line)

示例MAC地址是:“0024.c40c.4f45”

正则表达式给出的输出是“0024.c40c.4f4”,去掉了最后一个字符。我不明白它为什么要把它切断。有人能帮忙吗


Tags: 命令脚本身份验证log信息mac地址show
1条回答
网友
1楼 · 发布于 2024-09-27 00:21:55

使用

macpattern = re.compile(r"\b[A-Za-z0-9]{1,4}\.[A-Za-z0-9]{1,4}\.[A-Za-z0-9]{1,4}\b")
macResults = macpattern.findall(f.read())
print(macResults)

regex proof

整个文件用f.read()读入一个字符串变量,当您想要收集匹配项时使用它更方便

表达解释

                                        
  \b                       the boundary between a word char (\w) and
                           something that is not a word char
                                        
  [A-Za-z0-9]{1,4}         any character of: 'A' to 'Z', 'a' to 'z',
                           '0' to '9' (between 1 and 4 times
                           (matching the most amount possible))
                                        
  \.                       '.'
                                        
  [A-Za-z0-9]{1,4}         any character of: 'A' to 'Z', 'a' to 'z',
                           '0' to '9' (between 1 and 4 times
                           (matching the most amount possible))
                                        
  \.                       '.'
                                        
  [A-Za-z0-9]{1,4}         any character of: 'A' to 'Z', 'a' to 'z',
                           '0' to '9' (between 1 and 4 times
                           (matching the most amount possible))
                                        
  \b                       the boundary between a word char (\w) and
                           something that is not a word char

相关问题 更多 >

    热门问题