wibarr
wibarr

Reputation: 276

Grouping in Python Regular Expressions

So I'm playing around with regular expressions in Python. Here's what I've gotten so far (debugged through RegExr):

@@(VAR|MVAR):([a-zA-Z0-9]+)+(?::([a-zA-Z0-9]+))*@@

So what I'm trying to match is stuff like this:

@@VAR:param1@@
@@VAR:param2:param3@@
@@VAR:param4:param5:param6:0@@

Essentially, you have either VAR or MVAR followed by a colon then some param name, then followed by the end chars (@@) or another : and a param.

So, what I've gotten for the groups on the regex is the VAR, the first param, and then the last thing in the parameter list (for the last example, the 3rd group would be 0). I understand that groups are created by (...), but is there any way for the regex to match the multiple groups, so that param5, param6, and 0 are in their own group, rather than only having a maximum of three groups?

I'd like to avoid having to match this string then having to split on :, as I think this is capable of being done with regex. Perhaps I'm approaching this the wrong way.

Essentially, I'm attempting to see if I can find and split in the matching process rather than a postprocess.

Upvotes: 0

Views: 522

Answers (2)

rafalotufo
rafalotufo

Reputation: 3942

If this format is fixed, you don't need regex, it just makes it harder. Just use split:

text.strip('@').split(':')

should do it.

Upvotes: 3

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 799580

The number of groups in a regular expression is fixed. You will need to postprocess somehow.

Upvotes: 1

Related Questions