Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Extract all caps word contained in ANSI colored text

How might I extract this all caps word contained in regex with ANSI code for colored text in the terminal?

Example:

s1 = '      Elapsed: 0:00:59.694 - Elapsed/GB: 0:00:00.125 - Result: \x1b[92mPASS\x1b[0m\r\n'

My Failures:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

re.findall(r'- Result: [^\x1b[92m\x1b[0m\r\n]', s1)
re.findall(r'- Result: ([A-Z]+)', s1)

Expected:

PASS

>Solution :

Try this:

re.findall("\x1b\\[.*?m([A-Z0-9]+?)\x1b\\[", a)

So, first, if it will be the only colored thing in the line, then, start from the ANSI code itself.
Perceive that I did not prefixed the pattern with r, and let Python pre-treat the string – applying the \‘s before passing the string to the regex engine: this ensures \x1bis passed as the unicode code point for the <ESC> character. Also, the double slash before "[" to indicate it as literal.

The second thing is fixing the "m" in the regex as it is the command to actually change color attributes, without requiring any specific color to be set.

And last, but not least, use regex character range with [ ] to say
I want a word with caps (and digits) only, before another ANSI attribute command.

In [265]: a = s1 = '      Elapsed: 0:00:59.694 - Elapsed/GB: 

In [266]: re.findall("\x1b\\[.*?m([A-Z0-9]+?)\x1b\\[", a)
Out[266]: ['PASS']
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading