re.match value - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: re.match value (/thread-26230.html) |
re.match value - enigma619 - Apr-24-2020 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 koDoes anyone has an idea about this problem? Thanks Alex RE: re.match value - snippsat - Apr-24-2020 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") RE: re.match value - enigma619 - Apr-24-2020 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 RE: re.match value - bowlofred - Apr-24-2020 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'> RE: re.match value - snippsat - Apr-24-2020 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")
|