Parsing variable length data

Viewed 172

I'm using Python 3 and Im relatively new to RegEx. I'm struggling to come up with a good way to tackle the following problem. I have a text string (that can include line breaks etc) that contains a several sets of information.

For example:

TAG1/123456 TAG2/ABCDEFG HISTAG3/A1B1C1D1 QWERTY TAG4/0987654321 
TAG5/THE CAT SAT ON THE MAT MYTAG6/FLINTSTONE 
TAG7/99887766AA

I need this parsed to the following

TAG1/123456

TAG2/ABCDEFG

HISTAG3/A1B1C1D1 QWERTY

TAG4/0987654321

TAG5/THE CAT SAT ON THE MAT

MYTAG6/FLINTSTONE

TAG7/99887766AA

I can't seem to work out how to deal with the variable length tags :( TAG3 and TAG5 I always end up capturing the next tag i.e.

TAG5/THE CAT SAT ON THE MAT TAG6

In reality the TAGs themselves are also variable. Most are 3 characters followed by '/' but not all. Some are 4, 5 and 6 characters long. But all are followed by '/' and all EXCEPT the first one are preceded by a space

Updated Information I have updated the example to show these variable tags. But to clarify a tag can be 1-8 alphabetic characters, preceded by a space and terminated by '/' The data after the tag can be one or more words (alphanumeric) and is defined as all the data that follows the '/' of the tag up until the start of the next tag or the end of the string.

Any pointers would be greatly appreciated.

1 Answers

This is one way to achieve what you want I think:

import re

s = """TAG1/123456 TAG2/ABCDEFG TAG3/A1B1C1D1 QWERTY TAG4/0987654321 
TAG5/THE CAT SAT ON THE MAT TAG6/FLINTSTONE 
TAG7/99887766AA"""
r = re.compile(r'\w+/.+?(?=$|\s+\w+/)')
tags = r.findall(s)
print(*tags, sep='\n')

Output:

TAG1/123456
TAG2/ABCDEFG
TAG3/A1B1C1D1 QWERTY
TAG4/0987654321
TAG5/THE CAT SAT ON THE MAT
TAG6/FLINTSTONE
TAG7/99887766AA

The important bits are the non-greedy qualifier +? and the lookahead (?=$|\s+\w+/).

Related