[Tex/LaTex] How to insert complex regular expressions into tabularx cells

symbolstablestabularxverbatim

I'm trying to create a table with two columns, in which the second one is representing lots of regular expression with all the character you could imagine. I tried with \verb|text| command, but it gets stuck when there are '%' symbols and, if i try to escape them with a backslash, works but it compares in the result as '…\%…'. There is any solution that can help me escape ALL characters?

This is a snippet of my code

\begin{table}[H]
\centering
\begin{tabularx}{\textwidth}{cX}
    \toprule
    $Placeholder$&$Regular~Expression$\\ 
    \midrule
    URL&(https?:\/\/)?(www\.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,4}\b([-a-zA-Z0-9@:%_\+.~#?&//=]*)\\
    \bottomrule
\end{tabularx}
\caption{Regular Expressions}
\label{regex}\end{table}

UPDATE

Thank you for this workaround, works as expected! The reason why I used tabularx instead of tabular environment was because I had the necessity to manually break lines into the Regular Expression cell; with this solution seems to be still not possible, but better than nothing 🙂

Best Answer

As @DavidCarlisle has already indicated in a comment, you could proceed as follows: Use a tabular environment instead of a tabularx environment, use the p column type for the second column, and calculate its width using information about the width of the first column. This setup would allow the use the \url macro to typeset the long regexp string as if it were a URL string.

In the example below, using { and/or } is permissible because even though these characters occur in the regex string, they occur in the right order and are balanced. If this weren't the case, i.e., if the curly braces were unbalanced, one would have to use a character that doesn't occur anywhere in the regex string; e.g., \url!...! and \url M...M would both work since neither ! nor M occur in the regex string.

enter image description here

\documentclass{article}
\usepackage{booktabs}
\usepackage[spaces,hyphens]{url}

\newlength\lengtha
\newlength\lengthb
% Choose longest string in column A to calculate width
\settowidth{\lengtha}{\emph{Placeholder}}     
% Calculate width of column B as a residual
\setlength\lengthb{\dimexpr\textwidth-2\tabcolsep-\lengtha\relax} 

\begin{document}
\begin{table}
\begin{tabular}{@{} l p{\lengthb} @{}}
    \toprule
    \emph{Placeholder}&\emph{Regular~Expression}\\
    \midrule
    URL&  \url{(https?:\/\/)?(www\.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,4}\b([-a-zA-Z0-9@:%_\+.~#?&//=]*)} \\
    \bottomrule
\end{tabular}
\caption{Regular Expressions}
\label{regex}\end{table}
\end{document}