简体   繁体   中英

Python Regex Named Groups

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)

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(', '))
    })

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM