Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Match a pattern only when previous pattern matches

Tags:

python

regex

I have a situation where I have to match a pattern only when previous regex pattern matches. Both pattern are different and matchobj in different line. For exmaple,

Text:

blah blah blah MyHost="xxxx"
again blah blah blah MyIp= "x.x.x.x"

I am only interested in whats comes after MyHost and MyIp, I also have a requirement that MyIp should match only when there is a match(MyHost="xxxx") in the above line.

I am able to match both MyHost value and MyIp value separately but having hard time finding a logic to match both as per the requirement. Please note I am fairly new to python and tried lot of search and end up here.

like image 671
Sarvin Avatar asked Jun 10 '26 07:06

Sarvin


2 Answers

MyIp should match only when there is a match(MyHost="xxxx") in the above line.

Get the matched group from index 1 in Lazy way. You know already what is next after MyHost

\bMyHost="xxxx"\r?\n.*?MyIp=\s*\"([^"]*)

Here is demo

sample code:

import re
p = re.compile(ur'\bMyHost="xxxx"\r?\n.*?MyIp=\s*\"([^"]*)', re.IGNORECASE)
test_str = u"blah blah blah MyHost=\"xxxx\"\nagain blah blah blah MyIp= \"x.x.x.x\""

re.findall(p, test_str)
like image 116
Braj Avatar answered Jun 14 '26 01:06

Braj


You could do this through regex module.

>>> import regex
>>> s = '''blah blah blah MyHost="xxxx"
... foo bar
... again blah blah blah MyIp= "x.x.x.x"
... 
... blah blah blah MyHost="xxxx"
... again blah blah blah MyIp= "x.x.x.x"'''
>>> m = regex.search(r'(?<=MyHost="xxxx"[^\n]*\n.*?MyIp=\s*")[^"]*', s)
>>> m.group()
'x.x.x.x'

This would match the value of MyIp only if the string MyHost="xxxx" present on the previous line.

If you want to list the both, then try the below code.

>>> m = regex.findall(r'(?<=(MyHost="[^"]*")[^\n]*\n.*?)(MyIp=\s*"[^"]*")', s)
>>> m
[('MyHost="xxxx"', 'MyIp= "x.x.x.x"')]
like image 29
Avinash Raj Avatar answered Jun 13 '26 23:06

Avinash Raj



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!