remove digits NOT between brackets - regex

Viewed 149

I am trying to write a regular expression in python to remove digits except those between brackets here is an example : "[Verse 1: Bankroll Fresh] Dope boy, '[9]5 Air Max on Came from 1952.."

I would like : "[Verse 1: Bankroll Fresh] Dope boy, '[9] Air Max on Came from .."

2 Answers

Can you try this regex r'(?<!\[)\d+(?!\])'?

st = "[Verse 1: Bankroll Fresh] Dope boy, '[9]5 Air Max on Came from 1952.."
st = re.sub(r'\[\D*\d+\D*\]|(?<!\[)\d+(?!\])', lambda x: x.group(0) if x.group(0).startswith('[') else '', st)

# [Verse 1: Bankroll Fresh] Dope boy, '[9] Air Max on Came from ..
print(st)

(?<!\[) and (?!\]) are matches if \d+ NOT preceded by [ and NOT followed by ], respectively.

You can use the following code.

import re
 
s = "[Verse 1: Bankroll Fresh] Dope boy, '[9]5 Air Max on Came from 1952.."
 
pattern = r"\[.*?\]|(\d+)"

print(re.sub(pattern, lambda x: '' if x.group(1) else x.group(), s))
  -> [Verse 1: Bankroll Fresh] Dope boy, '[9] Air Max on Came from ..

Demo

The regular expression reads, "Match a left bracket followed by one or more characters matched lazily, followed by a right bracket, or match one or more digits and save the match to capture group 1."

Matching characters lazily prevents a right bracket from being matched. We could alternatively write the first part of the alternation \[[^\]]*\], where [^\]]* matches zero or more characters other than a right bracket.

The lambda reads, "If a string has been captured to group 1, replace the match with an empty string; else replace the match with itself".

Note that the order of the alternation is important; r"(\d+)|\[.*?\]" will not work.

Related