Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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)

>Solution :

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading