I have the following text



and the regular expression "\\begin{\([^}]*\)} to match the \begin statements and capture the comment or verbatim words. Now, I would like to match the \end statements. Given I already had a match for \begin I thought I could reference the previous match and look for \\end{\\1}, however I am getting Invalid back reference. Am I doing something wrong? Is there a way to reference previous matches in a regular expression?

  • 1
    Are you wanting to search for something like this? "\\\\begin{\\([^}]*\\)}\n.*?\n\\\\end{\\1}"
    – phils
    Apr 24, 2020 at 8:31
  • That's actually exactly what I wanted. It didn't cross my mind to use the one regex for both searches. Thanks you!
    – Tohiko
    Apr 24, 2020 at 8:33
  • You're welcome. I should add that, as . does not match newlines, the .*? should be \\(.\\|\n\\)*? if you needed it to match with arbitrary multi-line TEXT.
    – phils
    Apr 24, 2020 at 9:26

1 Answer 1


The \\1 construct is typically used when replacing the content.

If you do a search you have multiple options.

1) You could search for \\end{\([^}]*\)}" and manually check that the parts between the braces match the previous search.

2) You could create a regexp using normal string operations and search for it:

(concat "\\\\end{" (match-string 1) "}")
  • Thanks. For the second option, is there a way to do that more systematically from the regular expression \\end{\\1}? One way I thought would work is (replace-regexp-in-string "\\begin{\([^}]*\)}" "\\\\end{\\1}" (match-string 0)), but that didn't work for some reason.
    – Tohiko
    Apr 23, 2020 at 15:59
  • Correction: The expression (replace-regexp-in-string "\\begin{\([^}]*\)}" "\\\\end{\\1}" (match-string 0)) does work. I am now just wondering if it's the best way to go about doing this.
    – Tohiko
    Apr 23, 2020 at 16:47
  • 1
    In elisp, "\\begin{\([^}]*\)}" is the regexp \begin{([^}]*)} -- i.e. it starts with a word-boundary rather than "backslash followed by b", and there's no group, so it's not going to match. \\ and \( and \) all need to be escaped for the string read syntax.
    – phils
    Apr 24, 2020 at 8:27
  • What @phils is trying to say is that that when you write a regexp as a elisp string, you will need to write "\\\\begin{\\([^}]*\\)}". Apr 24, 2020 at 11:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.