Skip to content Skip to sidebar Skip to footer

Python Regex Split String While Keeping Delimiter With Value

I'm trying to parse a text file with name:value elements in it into lists with 'name:value'... Here's a twist: The values will sometimes be multiple words or even multiple lines

Solution 1:

Use a look-ahead assertion:

>>> re.split(r'\s(?=\w+:)', post)
['price:44.55',
 'name:John Doe',
 'title:Super Widget',
 'description:This widget slices, dices, and drives your kids to soccer practice\r\nIt even comes with Super Widget Mini!']

Of course, it would still fail if there are some words followed immediately by a colon in your values.

Solution 2:

@Pavel's answer is nicer, but you could also just merge together the results of your last attempt:

# killthefirstemptybitifnotdetails[0]:
    details.pop(0)

return[a + b for a, b in zip(details[::2], details[1::2])]

Post a Comment for "Python Regex Split String While Keeping Delimiter With Value"