简体   繁体   中英

python regex sub repeat specific pattern

i have some string data that contains characters from color coding.. i am trying to remove them using re.sub , but i can't figure out how to repeat my pattern. i thought +? would as it states 1 or more repetitions non-greedy. but it is only removing the "[0m" in the string not also the "[32m"

test = 'test1 test2                       [32mOK[0m'
test = re.sub(r'(.\[[\d*]m)+?', '', test)

how do make a regex that will remove any instance of the combination above leaving the text in between which in this instance is "OK" ??

my end goal here is to leave the OK text that is between [32 and [0m... OK could say FAILED or ERROR like this [32mFAILED[0m, [32mERROR[0m

You can try using the following pattern:

test = re.sub(r'(?:\[\d+m)', '', test)

This says to match [ followed by any number of digits, followed by m . Note that this would leave intact any content after the m .

Demo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM