0

I am trying to modify some LaTeX Beamer code, and want to do a quick regex find a certain pattern that defines a block of code. For example, in

\only{
      \begin{equation*}
            \psi_{w}(B)(1-B)^{d}y_{t,w} = x^{T}_{t,w}\gamma_{w} + \eta_{w}(B)z_{t,w},
            \label{eq:gen_arima}
        \end{equation*}
    }

I want to match just the \only{ and the final }, and nothing else, to remove them. Is that even possible?

Kartik
  • 8,347
  • 39
  • 73

2 Answers2

2

Regexes cannot count, as expressed in this famous SO answer: RegEx match open tags except XHTML self-contained tags

In addition, LaTeX itself has a fairly complicated grammar (i.e. macro expansions?). Ideally, you'd use a parser of some kind, but perhaps that's a little overkill. If you're looking for a really simple, quick and dirty hack which will only work for a certain class of inputs you can:

  • Search for \only.
  • Increment a counter every time you see a { and decrement it every time you see a }. If there is a \ preceding the {, ignore it. (Fancy points if you look for an odd number of \.)
  • When counter gets to 0, you've found the closing }.

Again, this is not reliable.

Mateen Ulhaq
  • 24,552
  • 19
  • 101
  • 135
  • 1
    I was afraid someone will say that. I guess I'll hack something together in bash... Thanks for the confirmation, and insight! – Kartik Jul 17 '17 at 01:27
1

I want to remove \only{ and }, and keep everything within it


On a PCRE (php), Perl, Notepad++ it's done like this:

For something as simple as this, all you need is
Find \\only\s*({((?:[^{}]++|(?1))*)})
Replace $2

https://regex101.com/r/U3QxGa/1

Explained

 \\ only \s*  
 (                             # (1 start)
      {
      (                             # (2 start), Inner core to keep
           (?:                           # Cluster group
                [^{}]++                       # Possesive, not {}
             |                              # or,
                (?1)                          # Recurse to group 1
           )*                            # End cluster, do 0 to many times
      )                             # (2 end)
      }
 )                             # (1 end)