Ishu Gupta
Ishu Gupta

Reputation: 1091

Regex to extract a particular string and assign it to a variable

I have following string :

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

I only need to extract "MASTER STATE" , "backup STATE", "Backup STATE" from the above strings , which will always appear after "VRRP_Instance(PC_VI) Entering" or "VRRP_Instance(PC_VI) Transition to". Right now , i have wrote the following:

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

It obviously is not right and picking up other strings as well. Please help.

Upvotes: 0

Views: 47

Answers (3)

Peter Brittain
Peter Brittain

Reputation: 13619

You just need to use alternation to find your two possible key strings instead of trying to match any of the individual letters in them.

For example:

.*VRRP_Instance.*.(Entering|Transition to) (?P<instance_state>.+

Upvotes: 1

Billy Moon
Billy Moon

Reputation: 58521

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

regexper diagram

Upvotes: 1

Vado
Vado

Reputation: 134

If Master and Backup states are the only states you have then you can use regex like this ((?:\bMASTER\b|\bBACKUP\b) STATE)$ with Multiline (m), Ignore case (i) and Global (g) modifiers.

Upvotes: 1

Related Questions