Search code examples
pythonregexre-python

Should I use regex or something else to extract log id from log files?


I have list with the following data:

["asdf mkol ghth", "dfcf 5566 7766", "7uy7 jhjh ffvf"]

I want to use regular expressions in python to get a list of tuples like this

[("asdf", "mkol ghth"),("dfcf", "5566 7766"),("7uy7", "jhjh ffvf")]

I tried using re.split, but I am getting an error saying too many values to unpack. following is my code:

logTuples = [()]
    for log in logList:
        (logid, logcontent) = re.split(r"(\s)", log)
        logTuples.append((logid, logcontent))

Solution

  • Regex is overkill here:

    l = ["asdf mkol ghth", "dfcf 5566 7766", "7uy7 jhjh ffvf"]
    
    lst = [tuple(i.split(maxsplit=1)) for i in l]
    
    print(lst)
    

    Prints:

    [('asdf', 'mkol ghth'), ('dfcf', '5566 7766'), ('7uy7', 'jhjh ffvf')]