File operations in Python
Question: I have a piece of code which extracts a string that lies between two
strings.However,this script performs this operation only on a line.I want to
perform this operation on a complete file and get a list of all the words
lying between those two words.

Note:The two words are fixed.For ex:If my code is something like

    
    
    'const int variablename=1'
    

then I want a list of all the words in the file lying between `'int'` and
`'='`. Here is the current script:

    
    
    s='const int variablename = 1'
    
    k=s[s.find('int')+4:s.find('=')]
    
    print k
    


Answer: If the file fits comfortably into memory, you can get this with a single regex
call:

    
    
    import re
    regex = re.compile(
    r"""(?x)
    (?<=    # Assert that the text before the current location is:
     \b     # word boundary
     int    # "int"
     \s     # whitespace
    )       # End of lookbehind
    [^=]*   # Match any number of characters except =
    (?<!\s) # Assert that the previous character isn't whitespace.
    (?=     # Assert that the following text is:
     \s*    # optional whitespace
     =      # "="
    )       # end of lookahead""")
    with open(filename) as fn:
        text = fn.read()
        matches = regex.findall(text)
    

If there can be only one word between `int` and `=`, then the regex is a bit
more simple:

    
    
    regex = re.compile(
    r"""(?x)
    (?<=    # Assert that the text before the current location is:
     \b     # word boundary
     int    # "int"
     \s     # whitespace
    )       # End of lookbehind
    [^=\s]*   # Match any number of characters except = or space
    (?=     # Assert that the following text is:
     \s*    # optional whitespace
     =      # "="
    )       # end of lookahead""")
    

