1

I want to colorize strings in python, inserting start/stop color sequences before/after all numbers, as well as substrings marked with a control character ( % ). Lets assume [ and ] are start/stop color sequence

Currently, I match the string using two substitute iterations:

Numbers: text = re.sub(r'(\d+(\.\d+)?)', '[\\1]', text)
Substrings: text = re.sub(r'%(.*?)%', '[\\1]', text)

Example string: "Test 1.23: Some %string 123 matched%"
Desired output: "Test [1.23]: Some [string 123 matched]"
Actual output: "Test [1.23]: Some [string [123] matched ]"

I've tried (in the number step) to detect if we are already in a colored area without luck, as well as removing all color tags within a %control character sequence%, also without luck.

7
  • 2
    that will happen obviously because of modification by your numbers re.sub..you cannot make them independent Commented May 26, 2016 at 11:09
  • This seems to work, but I'm not sure that it's really reliable... Commented May 26, 2016 at 11:14
  • @rock321987 I'm aware why it happens, just not how to fix it :) Commented May 26, 2016 at 11:19
  • @ThomasAyoub I've considered the option, but it fails when only one of the cases is present ( \2 is not present) Commented May 26, 2016 at 11:19
  • I've tested it and it works Commented May 26, 2016 at 11:23

1 Answer 1

2

There maybe other solutions but this may work. You need to install regex library for using branch reset feature.

>>> import regex as re
>>> x="Test 1.23: Some %string 123 match%ed"
>>> re.sub(r'(?|%(.*?)%|(\d+(?:\.\d+)?))', r'[\1]', x)
'Test [1.23]: Some [string 123 match]ed'
Sign up to request clarification or add additional context in comments.

2 Comments

I haven't heard of branch reset before, but this seems to work perfect. Thanks!
@AllanNørgaard i also haven't used it either till today one user pointed me about it here (today only) in comments..after seeing there I realized I can use that here

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.