首页 > 解决方案 > 如何编写正则表达式以从此表达式的第三行获取输出

问题描述

Netvisor OS Command Line Interface 5.1
Connected to Switch ugui-9kleaf1; nvOS Identifier:0xb00163e; Ver: 5.1.0-5010014593
Warning! ugui-9kleaf1's time is not in sync with the NTP Server.
CLI (network-admin@ugui-9kleaf1) > fabric-node-show format name no-show-headers

在此处输入图像描述

姓名

ugui-9kleaf1
ugui-9kleaf2
Warning! ugui-9kleaf1's time is not in sync with the NTP Server.

这是我的表达

我试过下面的正则表达式

r">.*[\r\n]?(.*)"

我得到的输出是

fabric-node-show format name, no-show-headers
ugui-9kleaf1
ugui-9kleaf2
Warning! ugui-9kleaf1's time is not in sync with the NTP Server.

我想要实际的输出。

ugui-9kleaf1
ugui-9kleaf2
Warning! ugui-9kleaf1's time is not in sync with the NTP Server.

上面的正则表达式正在捕获(命令+输出),但我只需要实际输出。

Netvisor OS Command Line Interface 5.1
Connected to Switch ugui-9kleaf1; nvOS Identifier:0xb00163e; Ver: 5.1.0-5010014593
Warning! ugui-9kleaf1's time is not in sync with the NTP Server.
CLI (network-admin@ugui-9kleaf1) >

>我的正则表达式中的符号将跳过我的正则表达式的横幅。

命令:fabric-node-show 格式名称,no-show-headers
输出我得到的内容: fabric-node-show format name, no-show-headers ugui-9kleaf1 ugui-9kleaf2 Warning! ugui-9kleaf1's time is not in sync with the NTP Server.

我想要的输出。

ugui-9kleaf1 ugui-9kleaf2 Warning! ugui-9kleaf1's time is not in sync with the NTP Server.

上面的正则表达式正在捕获(命令+输出),但我只需要实际输出。

注意:命令可能会不时更改,因此我可以对值进行硬编码。所以我想要一个通用的正则表达式,我每次只捕获实际输出。

标签: regexregex-negationregex-group

解决方案


我试过下面的正则表达式

r">.*[\r\n]?(.*)"

这差不多了。正如我们在您的图像中看到的,匹配组 1(绿色)包含所需输出的第一行,因此我们只需将匹配组 1 扩展到末尾。为此,我们可以使用标志s点匹配换行符),但不能用于整个正则表达式(因为它不能应用于第一个.),仅适用于组 1,因此我们必须使用内联修饰符 (?s)

r">.*[\r\n]?((?s).*)"

见网上。


推荐阅读