Search code examples
regexlatexlistings

How to use lstlisting package with regular expressions / special chars?


I want to show a php function with a regex in a code snippet using the lstlisting package. TeX gives me several errors "Package inputenc Error: Invalid UTF-8 byte sequence" and the dollar sign seems to put my tex code in math mode. The whole document is UTF-8 encoded. Any ideas how to correctly deal with these special chars in lstlisting environment? Thanks.

\usepackage[T1]{fontenc}
\usepackage[utf8]{inputenc}
\usepackage{listings}

\begin{lstlisting}[language=php,label={lis:mylisting}]
public function passes($attribute, $value)
{
  return preg_match("/^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[0-9])(?=.*?[#?!@()$%^&*=_{}[\]:;\"'|\\<>,.\/~`±§+-]).{8,255}$/", $value);
}
\end{lstlisting}

Solution

  • The problem is the plus-minus and section symbol. You can add specify them as literate:

    \documentclass{article}
    \usepackage[T1]{fontenc}
    \usepackage[utf8]{inputenc}
    \usepackage{listings}
    
    
    \begin{document}
    
    \begin{lstlisting}[language=php,label={lis:mylisting},extendedchars=true,literate={±}{{$\pm$}}1 {§}{{\S}}1]
    public function passes($attribute, $value)
    {
      return preg_match("/^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[0-9])(?=.*?[#?!@()$%^&*=_{}[\]:;\"'|\\<>,.\/~`±§+-]).{8,255}$/", $value);
    }
    \end{lstlisting}
    \end{document}