Does anyone know how to replace text in a string (Python) that is only between ( ) ? Example:
this is a string (replace the n here)
output:
this is a string (replace the p here) (turn the n into a p)
Conversation
This Tweet was deleted by the Tweet author. Learn more
This works provided that "replace the n here" does NOT also occur without parentheses somewhere else in the string - the replace() function will affect both!
Replying to
re.sub(r"(\([^)]*)( n )([^)]*\))", r"\1 p \3", "this is a string (replace the n here)")
1
6
Replying to
PS: i found this site which is really helpful!
18
Replying to
Try a regex like \([^\(\)]*?(n)[^\(\)]*?\) which should capture the smallest nested span of brackets that has an n inside. Might require running multiple times if nesting is possible. solution ignores nesting and may return cases with imbalanced parenthesis
1





