Search code examples
pythonregexend-of-line

Python regex: How to match a string at the end of a line in a file?


I need to match a string at the end of a line of a file.

The contents of the file are:

   network1:
     type: Internal

I have made this regex to get the first line but it does not match anything. Note that my code's requirement is that the string which is to be matched is stored in a variable. Therefore:

var1 = 'network1'
re.match('\s+%s:'%var1,line)

However, when I check this regex on the interpreter, it works.

>> import re 
>> line = '  network1:'
>> var1 = 'network1'
>> pat1 =  re.match('\s+%s:'%var1,line)
>> var2 = pat1.group(0)
>> print var2
     '  network1:'

Solution

  • You need to use re.search function, since match tries to match the string from the beginning.

    var1 = 'network1'
    print(re.search(r'.*(\s+'+ var1 + r':)', line).group(1))
    

    Example:

    >>> import re
    >>> s = 'foo network1: network1:'
    >>> var1 = 'network1'
    >>> print(re.search(r'.*(\s+'+ var1 + r':)', s).group(1))
     network1:
    >>> print(re.search(r'.*(..\s+'+ var1 + r':)', s).group(1)) # to check whether it fetches the last string or not.
    1: network1:
    

    So, you should do like

    with open(file) as f:
        for line in f:
            if var1 in line:
                print(re.search(r'.*(\s+'+ var1 + r':)', s).group(1))