Store output after finding matching string using regex and pexpect

Viewed 348

I'm writing a Python script and I am having some trouble figuring out how to get the output of a command I send and store it in a variable, but for the entire output of that command - I only want to store the rest of 1 specific line after a certain word.

To illustrate - say I have a command that outputs hundreds of lines that all represent certain details of a specific product.

Color: Maroon Red
Height: 187cm
Number Of Seats: 6
Number Of Wheels: 4
Material: Aluminum
Brand: Toyota 
#and hundreds of more lines...

I want to parse the entire output of the command that I sent which print the details above and only store the material of the product in a variable.

Right now I have something like:

child.sendline('some command that lists details')
variable = child.expect(["Material: .*"])
print(variable)
child.expect(prompt)

The sendline and expect prompt parts list the details correctly and all, but I'm having trouble figuring out how to parse the output of that command, look for a part that says "Material: " and only store the Aluminum string in a variable.

So instead of having variable equal to and print a value of 0 which is what currently prints right now, it should instead print the word "Aluminum".

Is there a way to do this using regex? I'm trying to get used to using regex expressions so I would prefer a solution using that but if not, I'd still appreciate any help! I'm also editing my code in vim and using linux if that helps.

2 Answers

You only need to look for the substring Material: . For this you can place the string you want to match (I am using a dot character, which means "match any character") in between a positive lookbehind for Material: and a positive lookahead for \r\n:

(?<=Material:\s).*(?=[\r\n])

You can find a good explanation for this regex here.

As you are using Python, you can use a capture group and store the value in for example my_var in the example code.

^Material:\s*(.+)

The pattern matches:

  • ^ Start of string
  • Material:\s* Match Material: and optional whitspace chars
  • (.+) Capture group 1 match 1+ times any char except a newline

See a regex demo and a Python demo.

For example

import re

regex = r"^Material:\s*(.+)"

s = ("Color: Maroon Red\n"
            "Height: 187cm\n"
            "Number Of Seats: 6\n"
            "Number Of Wheels: 4\n"
            "Material: Aluminum\n"
            "Brand: Toyota \n"
            "#and hundreds of more lines...")

match = re.search(regex, s, re.MULTILINE)
if match:
    my_var = match.group(1)
    print(my_var)

Output

Aluminum
Related