3

I am writing a scientific report and it demands me to write a bunch of masks, where a mask is typically a string with #, _ characters. For an example ###_#__##_##_#### is a mask. But latex does not let me write # in text and _ is interpreted as subsript.
I know I can use escape sequence (i.e.\#) to write the # character but I find it very cumbersome to write multiple such masks through out the paper. I am looking for an elegant way of making a text raw, such that it writes the text as such without any interpretation of the characters inside.
I could not find any relevant question answering this. Any help would be greatly appreciated.

EDIT: As few suggested, Command \textbackslash invalid in math mode this question answers but for a beginner, who would like to use raw strings, they cannot find the answer from this above mentioned question unless someone points to that. Hence, I would suggest keep this question closed, but not to remove it.

1 Answers1

6

You might use \verb|###_#__##_##_####|, but this has the problem that it cannot go in the argument to another command.

A different strategy might be to use 1 to denote # and 0 to denote the underscore. This way you can also very simply modify the final appearance by just acting on the definition.

\documentclass{article}

\ExplSyntaxOn

\NewDocumentCommand{\mask}{m} { % we want monospaced text \texttt { % process the input one character at the time \str_map_inline:nn { #1 } { % if the input is 1, output #`; if 0, output _ \str_case:nn { ##1 } { {0}{_} {1}{#} } } } }

\ExplSyntaxOff

\begin{document}

Here's a mask \mask{11101001101101111}

\end{document}

enter image description here

You can also preserve the original input, though; since token-to-string conversion doubles # characters, we need to normalize the stringified input and replace ## with # before mapping.

\documentclass{article}

\ExplSyntaxOn

\NewDocumentCommand{\mask}{m} { \texttt { \str_set:Nn \l_tmpa_str { #1 } \str_replace_all:Nxx \l_tmpa_str { \c_hash_str \c_hash_str } { \c_hash_str } \str_map_inline:Nn \l_tmpa_str { \str_case_e:nn { ##1 } { {\c_underscore_str}{_} {\c_hash_str}{#} } } } } \cs_generate_variant:Nn \str_replace_all:Nnn { Nxx }

\ExplSyntaxOff

\begin{document}

Here's a mask \mask{####__####_####}

\end{document}

The output is the same as before.

egreg
  • 1,121,712