Regex replace by pattern but preserv pattern itself

Viewed 51

I have two strings:

  1. [config.OPERATOR_ROLE]
  2. [config.MENEGER_ROLE]

I'm want replace it to

  1. {config.OPERATOR_ROLE}
  2. {config.OPERATOR_ROLE}

So I created a pattern \[config.*ROLE] which selecting all cases, but it replaces a pattern also, so my text going to be \{config.*ROLE}. How I can exclude part of pattern from replcaing?

2 Answers

You can still use re.sub with a capturing group in the repl argument:

>>> re.sub("\[config.(\S+)_ROLE\]", r"{config.\g<1>_ROLE}", "Hello [config.E_ROLE]")

Yields:

'Hello {config.E_ROLE}'

The trick is in the syntax \g<1> inside the repl string.

If you don't want to cross matching ] you could also use a negated character class to exclude matching ] or a whitespace char.

\[(config\.[^\s\]]*)_ROLE]

The pattern matches:

  • \[ Match [
  • ( Capture group 1 (denoted by \g<1> in the example code)
    • config\.[^\s\]]* Match config. followed by 0+ occurrences of any char excep ] or a whitespace char
  • ) Close group 1
  • _ROLE] Match literally

Regex demo | Python demo

Example code

import re

pattern = r"\[(config\.[^\s\]]*)_ROLE]"
s = ("[config.OPERATOR_ROLE]\n"
    "[config.MENEGER_ROLE]")
    
result = re.sub(pattern, r"{\g<1>_ROLE}", s)

if result:
    print (result)

Output

{config.OPERATOR_ROLE}
{config.MENEGER_ROLE}

If underscores are not allowed in the part before _ROLE and there can not be non whitespace character after the [ and ] you can use a bit more strict pattern

(?<!\S)\[(config\.[^\s_\]]*)_ROLE](?!\S)

Regex demo

Related