0

I am trying to use Regex multi group pattern to extract different CPU specs from a line, but getting an empty list.When i try individual groups separately, i am able to extract corresponding values. How should i use multi group pattern here? Please help!

import re

line = "R7000 CPU at 160MHz, Implementation 39, Rev 2.1, 256KB L2, 512KB L3 Cache"

pat_cpu_values_combined = r"(?P<freq>\s+\w+Hz)(?P<L2>\s+\w+\s+L2)(?P<L3>\s+\w+\s+L3)"
pat_cpu_freq = r"(?P<freq>\s+\w+Hz)"
pat_cpu_l2 = r"(?P<L2>\s+\w+\s+L2)"
pat_cpu_l3 = r"(?P<L3>\s+\w+\s+L3)"

# empty list coming when pat_cpu_values_combined is searched

print re.findall(pat_cpu_values_combined, line)

# below individual group pattern findall are working fine

print re.findall(pat_cpu_freq, line)
print re.findall(pat_cpu_l2, line)
print re.findall(pat_cpu_l3, line)

3 Answers 3

1

Your combined regex is looking for each of those patterns smashed together, with no intermediate characters. You can instead combine your patterns with the | separator.

pat_cpu_values_combined = r"(?P<freq>\s+\w+Hz)|(?P<L2>\s+\w+\s+L2)|(?P<L3>\s+\w+\s+L3)"

[''.join(g) for g in  re.findall(pat_cpu_values_combined, line)]
# returns:
[' 160MHz', ' 256KB L2', ' 512KB L3']
Sign up to request clarification or add additional context in comments.

1 Comment

No problem. Please remember to mark the question as answered.
0

When you combine them, you are not accounting for the characters in between the things you want to match. Try using this for your combined regex:

(?P<freq>\s+\w+Hz).*?(?P<L2>\s+\w+\s+L2).*?(?P<L3>\s+\w+\s+L3)

1 Comment

This did not work for me, with this pattern also i am getting empty list.
0

pat_cpu_values_combined expects strings matching your three individual patterns to occur with nothing in between them.

If you want to find all three in that order, use something like:

pat_cpu_values_combined = r"(?P<freq>\s+\w+Hz).*?(?P<L2>\s+\w+\s+L2).*?(?P<L3>\s+\w+\s+L3)"

Comments

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.