remove color codes from console text output

Viewed 523

I have a string which consists of color codes for some of the words. For example:

[38;2;139;0;0mHello [38;2;255;255;255m[38;2;128;128;128mWorld [38;2;255;255;255m

I need a way to remove these codes. Color code values are dynamics and keep changing but it has a pattern of [38;2;r;g;bm. The regular expression, using the above string, should return 'Hello World'.

I tried regular expression ^.*$ so far but it did not work.

I would like to do this in Python, not Perl, sed or Bash.

Any suggestion how can it be done? Or a valid regex to replace with ''.

1 Answers

You can create a regular expression for those color codes then use the Pattern.sub() method, passing an empty string as the first argument, to remove those unwanted parts.

A regular expression which matches the pattern provided ([38;2;r;g;bm):

\[\d{,3}(;\d{,3}){4}m

Using this regular expression with the sub() method and the test string provided:

>>> import re
>>> regex = re.compile(r"\[38;2(;\d{,3}){3}m")
>>> regex.sub("", "[38;2;139;0;0mHello [38;2;255;255;255m[38;2;128;128;128mWorld [38;2;255;255;255m")
'Hello World '
Related