Robust regex

J

Joseph L. Casale

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!

jlc
 
J

John Gordon

In said:
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!

Regexes may be overkill here. A simple string split might be better:

string = 'key_1|||value_1||||key_2|||value_2'
pairs = string.split('||||')
for pair in pairs:
keyval = pair.split('|||')
print '%s=%s' % (keyval[0], keyval[1])
 
J

Joseph L. Casale

Regexes may be overkill here. A simple string split might be better:

Yup, and much more robust as I was looking for.

Thanks everyone!
jlc
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,262
Messages
2,571,058
Members
48,769
Latest member
Clifft

Latest Threads

Top