There is a system command which gives output like this:
OUTPUT HDMI2 123.123.123
(OUTPUT) * HDMI1 124.124.124
How can I parse it? I need to parse, and I need data from the line with () and *, this is in used. When I got the in-used line I need the HDMI part and the numbers part.
1 Answer 1
Check if the line contains the string VGA, then return the numbers:
if 'VGA' in line:
return line.split('VGA')[1]
if "VGA" should be part of the result:
if 'VGA' in line:
return "VGA " + line.split('VGA')[1]
and, if you just want the numbers, individually:
if 'VGA' in line:
return map(int, line.split('VGA')[1].split('.'))
Update: solution for updated requirements.
To find the line marked with () and *, a regular expression might be better, e.g.:
for line in input_lines:
m = re.match(r'''
^\( # at the beginning of the line look for a (
[A-Z]+ # then a group of upper-case letters, i.e. OUTPUT
\) # followed by a )
\s* # some space
\* # a literal *
\s* # more space
(?P<tag>[A-Z0-9]+) # create a named group (tag) that matches HDMI1, ie. upper case letters or numbers
\s* # more space
(?P<nums>[\d\.]+) # followed by a sequence of numbers and .
$ # before reaching the end of the line
''', line, re.VERBOSE)
if m:
break
else: # note: this else goes with the for-loop
raise ValueError("Couldn't find a match")
# we get here if we hit the break statement
tag = m.groupdict()['tag'] # HDMI1
nums = m.groupdict()['nums'] # 124.124.124
answered Apr 21, 2016 at 7:10
thebjorn
27.6k12 gold badges107 silver badges152 bronze badges
Sign up to request clarification or add additional context in comments.
3 Comments
tmsblgh
I edited my question, I think you don't understand it, but its my fault. Sorry
thebjorn
Normally when asking a question on Stack Overflow, you need to (a) provide the input - which you have done, (b) the output you expect, and (c) the code you have tried. Right now I'm uncertain if you want
123.123.123 returned or 124.124.124?tmsblgh
I have these two line, these line are the output of an system command. I need to parse it and then I need the data of that line what is the active. The active line is always marked with * and (). The output what I want is this: "HDM1" or "124.124.124"
lang-py