3

I am trying to parse strings that look like shell commands. The general structure of these command is the following:

command value -arg1name arg1val -arg2name arg2val ... -argMname argMval

Here is an example,

abc cmdh1521 -x 123 -y sadg -zzz 563sd

I am using the Python re module to parse, search and group strings so that I get an output like this,

(command, value, ((-arg1name, arg1val), (arg2name, arg2val), ... (argMname, argMval))

I tried the following set of commands, but my output is not what I want it to be.

import re
cmd = "abc cmdh1521 -x 123 -y sadg -zzz 563sd"
_parser = r"^([a-z]+)\s{1}(\S*)((\s+\-[a-z]+\s{1}\S+)*)"
out = re.search(_parser, cmd)
print out.groups()

Here is the output I get

('abc', 'cmdh1521', ' -x 123 -y sadg -zzz 563sd', ' -zzz 563sd')

What am I doing wrong?

I can easily implement a non-regex solution, but I would like to know if there is a regex that can give me the kind of parsing I want?

2 Answers 2

2

In this case you will have to use positive lookbehind regex as shown below:

(?<=-)(\w+) ([\w\d]+) 

Description and example is at: Demo

Sign up to request clarification or add additional context in comments.

Comments

2

Then again split according to the space exists before -

>>> s = ('abc', 'cmdh1521', ' -x 123 -y sadg -zzz 563sd', ' -zzz 563sd')
>>> h = []
>>> for i in s:
    if '-' not in i:
        h.append(i)
    else:
        for j in re.split(r'\s+(?=-)', i):
            if j:
                h.append(j)


>>> h
['abc', 'cmdh1521', '-x 123', '-y sadg', '-zzz 563sd', '-zzz 563sd']
>>> 

or

>>> cmd = "abc cmdh1521 -x 123 -y sadg -zzz 563sd"
>>> import re
>>> re.findall(r'^(\S+)\s+(\S+)|(-\S+\s+\S+)', cmd)
[('abc', 'cmdh1521', ''), ('', '', '-x 123'), ('', '', '-y sadg'), ('', '', '-zzz 563sd')]
>>> [j for i in z for j in i if j ]
['abc', 'cmdh1521', '-x 123', '-y sadg', '-zzz 563sd']
>>> 

1 Comment

Can I get the kind of parsing I want without having to resort to manually segmenting these individual strings like you have done?

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.