Monday, 20 May 2013

Checking if a string contains # with its original catcode

Checking if a string contains # with its original catcode

At comp.text.tex the following scheme was suggested for testing if a string contains the parameter character with catcode 6.
\def\endcheck{\endcheck}
\def\second#1#2{#2}
\def\gobbletocheck#1\endcheck#2#3{#2}
\def\checkhash#1{\docheckhash#1\endcheck}
\def\docheckhash#1{%
  \ifx#1\endcheck
    \expandafter\second
  \else
    \ifx#1##%
      \expandafter\expandafter\expandafter\gobbletocheck
    \else
      \expandafter\expandafter\expandafter\docheckhash
    \fi
  \fi
}
This can be called as
\checkhash{abc#def}{YES}{NO}
\checkhash{abcdef}{YES}{NO}
Obviously, as suggested by its author, this test fails if the string to test contains brace groups with the first two tokens identical, e.g.,
\checkhash{ab{cc}def}{YES}{NO}
Please can anyone suggest a better test? Please note that the catcode of the hash character must be 6, not 12.
An expandable solution will be beautiful but not a necessity.

No comments:

Post a Comment