0

I'm currently trying to solve a problem splitting following string

[@x arg-xa, arg. xb, arg xc @y arg-ya, arg. yb, arg yc @z arg-za, arg. zb, arg zc]

into some kind of structured dict object. A result like the following list would be appreciated:

[
    {
        'command': 'x',
        'args': ['arg-xa', 'arg. xb', 'arg xc']
    },
    {
        'command': 'y',
        'args': ['arg-ya', 'arg. yb', 'arg yc']
    }
    {
        'command': 'z',
        'args': ['arg-za', 'arg. zb', 'arg zc']
    }
]

The command is prefixed with an "@" sign, the following arguments for the command are separated by a "," sign. Splitting the string with string.split('@') and some loops would work, but I'm wondering if it would be possible to solve this with one single regex.

Maybe some regex master would be so kind and show me the light!

As always, thank's a lot. (I used the search, but haven't found a solution for this kind of problem)

1
  • This pretty weird regex: \@(?P<command>\w+)(?P<arg>,\s?[\w\s-]+)\@? Commented Jan 1, 2013 at 15:58

1 Answer 1

2

I'd just use .split() and cut the string up:

import string

s = '@x arg-xa, arg. xb, arg xc @y arg-ya, arg. yb, arg yc @z arg-za, arg. zb, arg zc'

result = []

for part in s.split('@')[1:]:  # `[1:]` skips the first (empty) element
    command, _, arguments = part.partition(' ')

    result.append({
        'command': command,
        'args': map(string.strip, arguments.split(', '))
    })
Sign up to request clarification or add additional context in comments.

7 Comments

Yeah, it does work - I don't use Python much. I think it can be improved a bit by trimming spaces, though.
@Blender Thank's for your solution! Really appreciate it. But I know that it works with string.split method and loops. I was specificaly interested in a regex. Sure, your's is working and if no regex comes up, I'm happy to accept your answer...
@Blender: There are some excessive space at the end of last argument of the 1st and 2nd item in result.
@hetsch: You won't be able to do it with just regex.
@Blender Think you are right. Trying now for some time, but no result. Really like your solution. Thank's again for your help, accepted!
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.