Match a pattern only when previous pattern matches
Question: 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.


Answer: > `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](http://regex101.com/r/sB6mR7/4)

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)
    

