Beth Savis
Beth Savis

Reputation: 77

Parsing a Parse format string in python

I am trying to parse a string in python and have been using Parse from PyPi (https://pypi.python.org/pypi/parse) to do all of my parsing.

However, I now need to parse the string that the Parse library uses for it's parsing format.

For example, the string:

{time:ti}|{dogColor:w}|{dogAge:d}|{startaddress:w}|

I am using a similar format (not about dogs) to parse a log file. However, I would like to parse this string as well in order to find the type of each individual item (parse the string to find the 'ti' after time to know that it is a time object, or the w after 'dogColor' to know it is a string)

First, I am splitting the line by the '|' character, which results in:

{time:ti}

From here I would like to parse out each side of the colon, and not include the curly braces. I have tried this to no avail:

result = parse('{{name}}:{type}', token)

I think the issue I am having is that the Parse library cannot parse curly braces as that is a special character? I have tried escape characters to no avail like so:

result = parse("/{{name}/}:{type}", token)

Any recommendations? Is there maybe a better way to do this without the Parse library?

Upvotes: 2

Views: 2640

Answers (1)

wim
wim

Reputation: 362478

Double curly braces to escape them:

>>> parse('{{{}:{}}}', '{time:ti}')
<Result ('time', 'ti') {}>

Upvotes: 2

Related Questions