gpt4 book ai didi

regex - 如何使用单行解析需要多个匹配项的 csv 输出?

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:20:55 25 4
gpt4 key购买 nike

我有一个场景,我从数据库中取出后处理/过滤值。我正在使用 perl ple 来完成这项任务。一切正常,直到我遇到包含多个 text 标签的提取输出 (csv)。参见示例 here .如果只有一个文本标签,代码也能正常工作(提取正则表达式)。在我的数据库中,有些情况下有多个文本文件(即规则条件)。

代码是

echo "COPY (SELECT rule_data FROM custom_rule) TO STDOUT with CSV HEADER" | psql -U qradar -o /tmp/Rules.csv qradar;
perl -ple '
($enabled) = /(?<=enabled="").*?(?="")/g;
($group) = /(?<=group="").*?(?="")/g;
($name) = /(?<=<name>).*?(?=<\/name>)/g;
($text) = /(?<=<text>).*?(?=<\/text>)/g;
$_= "$enabled;$group;$name;$text";
s/&lt;.*?&gt;//g;
' Rules.csv > rules_revised.csv

只需在示例输出上运行代码,我就会在 rule_revised 文件中获得以下内容。

true;Flow Property Tests;DoS: Local Flood (Other);when the flow bias is any of the following outbound

实际上,该行在 outbound 之后被截断,实际上应该携带类似这样的信息..

when at least 3 flows are seen with the same Source IP, Destination IP in 5 minutes and when the IP protocol is one of the following IPSec, Uncommon and when the source packets is greater than 60000

已尝试通过使正则表达式贪婪地删除 $text 中的 ? 来纠正此问题,但随后它会溢出 text 之间的所有内容直到最后一个 text 并在最后删除 lt;.*?> 把剩下的弄乱了,因为它包含了我最初打算取消的所有标记字符(即 html)元素在进行正则表达式贪婪更改之前包含。

最佳答案

您获得包含多个匹配项的截断结果的原因是您只存储了第一个匹配项。

($text)    = /(?<=<text>).*?(?=<\/text>)/g;

这只存储第一个匹配项。如果将该标量更改为数组,您将捕获所有匹配项:

(@text)    = /(?<=<text>).*?(?=<\/text>)/g;

当您插入数组时,它会在元素之间插入空格($" 的值)。如果您不想这样,您可以更改 $"< 的值 到可接受的分隔符。为了清楚起见,您将更改两个字符以获得以下行:

(@text)    = /(?<=<text>).*?(?=<\/text>)/g;
...
$_= "$enabled;$group;$name;@text";

如果我使用这些更改在您的示例上运行您的代码,输出将如下所示:

false;Flow Property Tests;DoS: Local Flood (Other);when the flow bias is any of the following outbound when at least 3 flows are seen with the same Source IP, Destination IP in 5 minutes when the IP protocol is one of the following IPSec, Uncommon when the source packets is greater than 60000

关于regex - 如何使用单行解析需要多个匹配项的 csv 输出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21853060/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com