Farhood Farhood - 3 years ago 97
Python Question

How to extract data from formatted string using python?

I have a set of strings like this:


C001F01.PNG

C001G01.PNG

C002F10.PNG


which follow the format of :


C(id number)(F or G)(another id number).PNG


I want to know their ids' and know if they were from class F or G, I have read that
re.split()
could do similar work, but I'm confused and don't understand how RE works exactly.

Answer Source

You should certainly read more on regex. A first hint is that when you want to capture a pattern you need to enclose it in parentheses. e.g. (\d+). For this example though, the code you need is:

match = re.match(r'C(\d+)([F|G])(\d+)\.PNG', s)

first_id = match.group(1)
fg_class = match.group(2)
second_id = match.group(3)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download