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)
>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[_ngstring (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)