Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
re.match value
#1
Hi
I've a question about match value in python.

On a server I've installed a tool edac-utils. When I launch this command, result is:
[server]edac-util
mc1: 1257 Corrected Errors with no DIMM info


    try:
        output = subprocess.check_output("edac-util", shell=True)
    except subprocess.CalledProcessError as error:

    for line in output.splitlines():
        line = str(line)

        if re.match('^mc1\:\ 1253\ Corrected\ Errors\ with\ no\ DIMM\ info$', line):
            print ("match ok")
        else:
            print ("match ko")
(I put all the output on my regex because it doesnt work but there it not works too..)

Result is

match ko
Does anyone has an idea about this problem?

Thanks

Alex
Reply
#2
Try use re.search() instead.
Don't need all those escape \ to match that line.
try:
    output = subprocess.check_output("edac-util", shell=True)
except subprocess.CalledProcessError as error:
    pass

for line in output.decode().splitlines():
    if re.search(r'mc1: 1257 Corrected Errors with no DIMM info', line):
        print ("match ok")
    else:
        print ("match ko")
Reply
#3
Thanks for your answer, it works !

I'm trying to understand.
On docs I see:
search ⇒ find something anywhere in the string and return a match object.
match ⇒ find something at the beginning of the string and return a match object

I'm not sure to understand why it doesn't work with my first solution ? (even without the \)

Thanks!
Alex
Reply
#4
As we don't have your data, it's hard to tell why it doesn't work (we can't tell what line is set to). Perhaps you have trailing spaces or something. Put your data in the post as well if you want someone to examine it. But you're right, it could work (depending on the data).

>>> s = 'mc1: 1257 Corrected Errors with no DIMM info'
>>> re.match('^mc1\:\ 1257\ Corrected\ Errors\ with\ no\ DIMM\ info$', s)
<re.Match object; span=(0, 44), match='mc1: 1257 Corrected Errors with no DIMM info'>
Reply
#5
As mention bye @bowlofred match could work it depend on data.
Also use repr() this is powerful way(to see all) that often is forget in debugging.
import re

output = '''\
aaaaaaaaaaa 1111111111111
mc1: 1257 Corrected Errors with no DIMM info
22222222222222 yyyyyyyyyyyy
mc1: 1257 Corrected Errors with no DIMM info'''

for line in output.splitlines():
    print(repr(line))
    if re.match(r'^mc1: 1257 Corrected Errors with no DIMM info$', line):
        print ("match ok")
    else:
        print ("match ko")

Output:
'aaaaaaaaaaa 1111111111111' match ko 'mc1: 1257 Corrected Errors with no DIMM info' match ok '22222222222222 yyyyyyyyyyyy' match ko 'mc1: 1257 Corrected Errors with no DIMM info' match ok
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020