I'm trying to replace the parenthesis inside a certain tag to just outside of the tag i.e. if there is a opening parenthesis immediately after the tag or a closing parenthesis immediately before the closing tag. Example:
<italic>(When a parenthetical sentence stands on its own)</italic>
<italic>(When a parenthetical sentence stands on its own</italic>
<italic>When a parenthetical sentence stands on its own)</italic>
Those lines should be after replace:
(<italic>When a parenthetical sentence stands on its own</italic>)
(<italic>When a parenthetical sentence stands on its own</italic>
<italic>When a parenthetical sentence stands on its own</italic>)
However, strings like the the next three below should stay untouched.
<italic>(When) a parenthetical sentence stands on its own</italic>
<italic>When a parenthetical sentence stands on its (own)</italic>
<italic>When a parenthetical sentence stands (on) its own</italic>
But the following strings:
<italic>((When) a parenthetical sentence stands on its own</italic>
<italic>((When) a parenthetical sentence stands on its own)</italic>
<italic>(When) a parenthetical sentence stands on its own)</italic>
<italic>When a parenthetical sentence stands on its (own))</italic>
<italic>(When a parenthetical sentence stands on its (own)</italic>
should be after the replace(s):
(<italic>(When) a parenthetical sentence stands on its own</italic>
(<italic>(When) a parenthetical sentence stands on its own</italic>)
<italic>(When) a parenthetical sentence stands on its own</italic>)
<italic>When a parenthetical sentence stands on its (own)</italic>)
(<italic>When a parenthetical sentence stands on its (own)</italic>
There could be nested tags inside the <italic>...</italic>
tags and a line can contain multiple <italic>...</italic>
strings.
Also if there is a nested tag <inline-formula>...</inline-formula>
inside <italic>...</italic>
then those should be ignored.
Can I do this using regex? If not what other way can I do this?
My approach is this (I am still not sure if it covers all possible cases):
1st step: <italic>( ---> (<italic>
find <italic>
( if the tag is not followed by a matching pair of parenthesis immediately not followed by a closing tag
The match is allowed only within a single line.
Find what: (<(italic)>)(?!(\((?>(?:(?![()\r\n]).)++|(?3))*+\))(?!</$2\b))(\()
Replace with: $4$1
2nd step: )</italic> ---> </italic>)
find )</italic>
if the tag is not preceded by a matching pair of parenthesis immediately not preceded by an opening tag
The match is allowed only within a single line.
(\))(?<!(?<!<(italic)>)(\((?>(?:(?![()\r\n]).)++|(?3))*+\)))(</2\b>)