1

I have a large LaTeX document where I have defined a macro like this:

\newcommand{\abs}[1]{\left|#1\right|}

I want to get rid of it by replacing in all the document \abs{...} by \left|...\right|, so I am thinking in a regular expression. I am familiar with their basics but I do not know how to find the bracket that closes the expression, given that the following situations are possible:

  1. \abs{(2+x)^3}
  2. \abs{\frac{2}{3}}
  3. \abs{\frac{2}{\sin(2\abs{x})}}

What I have been able to do for the moment is \\abs\{([^\}]*)\} and then replace as \left\1\right|but it is only able to deal with the pieces of code of the first kind only.

By the way, I am using the TeXstudio regular expression engine.

epsilone
  • 735
  • 10
  • 20
  • You may find help over at [tex.stackexchange](http://tex.stackexchange.com/). – Celeo Sep 24 '14 at 23:27
  • 2
    Thanks @Celeo, but since this is a question more related with regular expressions than with LaTeX I think it fits better here. – epsilone Sep 24 '14 at 23:29

1 Answers1

2

Well, I did a little more of research and I managed to solve it. According to this response in a similar question, it suffices to use recursive regular expressions and a text editor that supports them, for example Sublime Text 2 (I could not do it with TeXstudio). This does the trick:

Find: \\abs\{(([^\{\}]|(?R))*)\}

Replace: \\left|\1\\right|

EDIT 1: Actually this solves only the two first cases, but fails with the third, so any idea on how to improve the regular expression would be appreciated.

EDIT 2: See comment from @CasimiretHippolyte for full answer using \\abs\{((?>[^{}]+|\{(?1)\})*)\}

Community
  • 1
  • 1
epsilone
  • 735
  • 10
  • 20
  • Good research effort. You can try it without escaping the curly brackets. Or better, if supported: `\\abs{((?>[^{}]+|{(?1)})*)}` – Casimir et Hippolyte Sep 25 '14 at 00:49
  • @CasimiretHippolyte Humm that one does not seem to be supported. Actually, I have edited the answer since the solution for the third case is still open. – epsilone Sep 25 '14 at 01:19
  • 1
    It seems that you must to escape curly brackets that are out of a character class in sublimetext2, so: `\\abs\{((?>[^{}]+|\{(?1)\})*)\}` *(the `(?1)` repeats the subpattern in the capture group 1, `(?R)` repeats the whole pattern)* – Casimir et Hippolyte Sep 25 '14 at 01:25
  • @CasimiretHippolyte Great! That works like a charm! Would you mind turning your comment as an answer so I can accept it? – epsilone Sep 25 '14 at 01:40