Replacing parts of expressions in Sublime Text?

473 views Asked by At

I'm using regex find and replace feature in Sublime Text 3, searching for expressions of the form (\cref{exNUMBER}) or (\cref{exNUMBERLETTER}) For example:

(\cref{ex1})
(\cref{ex1a})

The following regex finds these expressions just fine:

\(\\cref\{ex(\d|\d\l)\}\)

What I'm struggling with is how to replace these same expressions with expressions of the form \eqref{exNUMBER} or \eqref{exNUMBERLETTER}. For example, the above examples would produce:

\eqref{ex1}
\eqref{ex1a}

I've tried doing a roughly parallel construction, \\eqref\{ex(\d|\d\l)\}, but all that produces when I replace is the following: \eqref{ex(d|d)}.

What is the correct way to use regex wildcards while replacing in Sublime Text 3 so that I can replace (\cref{exNUMBER}) or (\cref{exNUMBERLETTER}), with \eqref{exNUMBER} or \eqref{exNUMBERLETTER} (respectively)?

2

There are 2 answers

1
Bohemian On BEST ANSWER

Capture what you want to keep in a group (so you can put it back in the replace):

\(\\c(ref\{ex(\d|\d\l)\})\)
     ^                  ^

Markers indicate brackets added to capture stuff you want to keep as a group (group 1).

And replace matches with:

\eq\1

The \1 is a back reference to group 1 - it outputs what was captured in the match.

0
Owen On

Bohemian's answer is perfect and should be the accepted answer. I am just adding something simpler as well, since w/ the complexity of the OP's regular expression I found it a bit hard to follow. For a simpler case, imagine we had a text file containing:

345
3234
23423

which we wanted to convert to:

{ value: 345 }
{ value: 3234 }
{ value: 23423 }

The correct syntax for the find/replace would be:

  • Find: (\d+)
  • Replace: { value: \1 }

Bohemian's answer explains the logic behind this really clearly, just with a lot more slashes :).