Escape character in LaTeX

The following ten characters have special meanings in (La)TeX:

& % $ # _ { } ~ ^ \

Outside \verb, the first seven of them can be typeset by prepending a backslash; for the other three, use the macros \textasciitilde, \textasciicircum, and \textbackslash.

\documentclass{article}

\begin{document}

\& \% \$ \# \_ \{ \}

\textasciitilde

\textasciicircum

\textbackslash

\end{document}

enter image description here

Note that the seven "single non-letter" macros don't gobble the space following them. For the last three that do gobble up the space after them you can try one of these methods to add space.


Usually text like that is typeset in typewriter type and so there's a slick way to arrange it

\verb|[RegularExpression(@"\d+")]|

After \verb should go a character that's not used in the text to print "verbatim" and the same character should follow the text.

This command has a drawback: it can't be used in the argument of other commands.

There's a second "solution" which can come handy if it's needed a limited number of times:

\texttt{[RegularExpression(@"\string\d+")]}

where commands inside the argument to \texttt are allowed. It's not even necessary to use \texttt:

\textsf{[RegularExpression(@"\string\d+")]}

will work as well (when T1 font encoding is active) and will print the string in sans serif type.


I needed a way to escape all special characters and I found this Perl function:

sub latex_escape {
  my $paragraph = shift;

  # Replace a \ with $\backslash$
  # This is made more complicated because the dollars will be escaped
  # by the subsequent replacement. Easiest to add \backslash
  # now and then add the dollars
  $paragraph =~ s/\\/\\backslash/g;

  # Must be done after escape of \ since this command adds latex escapes
  # Replace characters that can be escaped
  $paragraph =~ s/([\$\#&%_{}])/\\$1/g;

  # Replace ^ characters with \^{} so that $^F works okay
  $paragraph =~ s/(\^)/\\$1\{\}/g;

  # Replace tilde (~) with \texttt{\~{}}
  $paragraph =~ s/~/\\texttt\{\\~\{\}\}/g;

  # Now add the dollars around each \backslash
  $paragraph =~ s/(\\backslash)/\$$1\$/g;
  return $paragraph;
}

For example it will convert this:

& % $ # _ { } ~ ^ \ \today

into this:

\& \% \$ \# \_ \{  \} \texttt{\~{}} \^{} $\backslash$ $\backslash$today