Jonathan Lebrun
Jonathan Lebrun

Reputation: 1552

How to remove string starting with another string inside brackets?

I have this kind of string:

hello[_ng11][test]hello3[_ngRTf]

and I would like to remove string starting with _ng inside brackets

Result should be:

hello[][test]hello3[]

I did try to do something like this:

st = "hello[_ng11][test]hello3[_ngRTf]"
modified_string = re.sub(r"/\[\[_ng[^\]]*\]\]/", "[]", st)
print(modified_string)

Upvotes: 0

Views: 39

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626893

You need to remove the slashes and reduce square brackets to a single occurrence on both sides of the pattern:

modified_string = re.sub(r"\[_ng[^][]*]", "[]", st)

See the Python demo:

import re
st = "hello[_ng11][test]hello3[_ngRTf]"
modified_string = re.sub(r"\[_ng[^][]*]", "[]", st)
print(modified_string)
# => hello[][test]hello3[]

Details:

  • \[_ng - a [_ng string (only the [ char is special here)
  • [^][]* - zero or more chars other than ] and [ (smart placing, ] is the first char in the character class and thus does not need escaping)
  • ] - a ] char (it is not special outside of a character class)

Upvotes: 1

Related Questions