正则表达式提取特定字符串并将其分配给变量

时间:2015-07-20 20:50:57

标签: regex

我有以下字符串:

Jul 20 16:47:43 chefawsdeveastbck2 dhclient[1036]: bound to 10.205.5.122 -- renewal in 1797 seconds.
Jul 17 18:07:15 chefawsdeveastbck2 Keepalived_vrrp[937]: VRRP_Instance(PC_VI) Sending gratuitous ARPs on eth0 for 10.205.5.121
Jul 17 18:07:10 chefawsdeveastbck2 Keepalived_vrrp[937]: VRRP_Instance(PC_VI) Sending gratuitous ARPs on eth0 for 10.205.5.121
Jul 17 18:07:10 chefawsdeveastbck2 Keepalived_vrrp[937]: VRRP_Instance(PC_VI) setting protocol VIPs.
Jul 17 18:07:10 chefawsdeveastbck2 Keepalived_vrrp[937]: VRRP_Instance(PC_VI) Entering MASTER STATE
Jul 17 18:07:09 chefawsdeveastbck2 Keepalived_vrrp[937]: VRRP_Instance(PC_VI) Transition to MASTER STATE
Jul 17 18:07:09 chefawsdeveastbck2 Keepalived_vrrp[937]: VRRP_Instance(PC_VI) Transition to Backup STATE

我只需要提取" MASTER STATE" ,"备份STATE","备份状态"来自上面的字符串,它将始终出现在" VRRP_Instance(PC_VI)Entering"或" VRRP_Instance(PC_VI)过渡到"。 现在,我写了以下内容:

.*(VRRP_Instance.*.[EnteringTransitionto]+ )(?P<instance_state>.+)

显然这是不对的,也可以选择其他字符串。请帮忙。

3 个答案:

答案 0 :(得分:1)

如果 Master 备份状态是您拥有的唯一状态,那么您可以使用带有Multiline(m)的((?:\bMASTER\b|\bBACKUP\b) STATE)$这样的正则表达式,忽略大小写(i) )和全球(g)修饰符。

答案 1 :(得分:1)

/VRRP_Instance\(PC_VI\) (?:Entering|Transition to) ((?:MASTER|[bB]ackup) STATE)/

regexper diagram

答案 2 :(得分:1)

您只需要使用替换来查找两个可能的关键字符串,而不是尝试匹配其中的任何单个字母。

例如:

<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
<div id="multiline"></div>