Robust regex

MRAB python at mrabarnett.plus.com
Mon Nov 19 15:50:46 EST 2012


On 2012-11-19 20:32, Joseph L. Casale wrote:
> Trying to robustly parse a string that will have key/value pairs separated
> by three pipes, where each additional key/value (if more than one exists)
> will be delineated by four more pipes.
>
>      string = 'key_1|||value_1||||key_2|||value_2'
>      regex = '((?:(?!\|\|\|).)+)(?:\|\|\|)((?:(?!\|\|\|).)+)(?:\|\|\|\|)?'
>
> I am not convinced this is the most effective or safest, any opinions would
> be greatly appreciated!
>
Do you need to use regex?

It would be simpler to use the .split method:

for pair in string.split("||||"):
     key, value = pair.split("|||")
     print("key is {!r}, value is {!r}".format(key, value))




More information about the Python-list mailing list