[英]Create a regex with target text having varying key-value pairs?
我正在编写一些正则表达式来执行一些配置文件验证自动化,我打算将其包含到 CICD 管道中,但我面临一些问题,让正则表达式在某些字符串上正常工作。
我有如下字符串:
Filter:Class=RBSG_Root_Base;
Filter:Class=Logfile_Base;
Filter:Class=Logfile_Sendmail;
Filter:Class=Daemon_Notice;
Filter:Class=Logfile_Syslogd;msg=re:'syslogd: restart';
Filter:Class=Logfile_Cron;msg=re:'CMD';
Filter:Class=Logfile_Cron;msg=re:'STARTUP';
Filter:Class=AppLog;sub_source=MTResourceMonitor;msg=re:'support';
规则是:
我需要使用一些正则表达式来验证它们,但是当它们中有多个键值对时,我很难让它正确匹配字符串。 不过,它只适用于单个键值对。
例如,以下字符串可以很好地匹配:
Filter:Class=Logfile_Base;
但是,以下内容不正确匹配:
Filter:ClassAppLog;sub_sourceMTRMonmsg=re:'su;dnsdjs;
上面那个字符串的开头和结尾很好,但是键值对之间没有分号分隔符,所以它实际上是无效的。 它违反了第 3 条规则。
这是我迄今为止创建的正则表达式,有时如上所示:
^Filter:.*=.*;$
使用您显示的示例,请尝试以下正则表达式。
^Filter:(?:\w+=[^;]*;)*$
说明:为上述正则表达式添加详细说明。
^Filter: ##Matching Filter: from starting of value.
(?: ##Starting a non-capturing group from here.
\w+=[^;]*; ##Matching \w(1 or more occurrences) followed by = till a semi colon comes, including ; in match.
)*$ ##Matching 0 or more occurrences of regex mentioned above till end of value.
注意:将上面的正则表达式更改为^Filter:(?:\w+=[^;]*;)+$
以防您想匹配至少 1 个匹配的值 - 键对,这里只有在正则表达式中从*
更改为+
.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.