7

I want to detect whether an input line contains a certain substring, similar to the problem discussed here: Check if a string contains a given character

The complicating problem is that the match strings look like these:

%* tex 1;
%* pgm 4;

The first step is to find whether I have a match. I'm trying to do this using the xstring package. The following code is my attempt to get started, just to test whether the string contains a % sign. It complains that the paragraph ended before \x was complete.

\begingroup
  \catcode`\%=12\relax
  \def\x#1{\def\dotest{\catcode`\%=12\relax\IfSubStr{#1}{%}{YES}{NO}}}
  \expandafter\endgroup\x

The complete task is to read a line and:

  1. find whether there is match,
  2. what type it is (tex or pgm) and
  3. read the trailing number into a counter
  4. possibly pass the line to a verbatim environment or external file.

Basically I'm constructing a mini-language to be used as a code environment.

Tim A
  • 1,945

1 Answers1

5

This should be what you are loooking for:

\documentclass{minimal}
\usepackage{xstring}
\usepackage[T1]{fontenc}
\begingroup
\makeatletter
\catcode`\%12
\gdef\ifpourcent{\catcode`\%12 \ifpourcent@i}
\gdef\ifpourcent@i#1{\IfSubStr{#1}{%}}
\endgroup
\begin{document}
\ifpourcent{% tex1;}{YES}{NO}

\ifpourcent{abcd ef}{YES}{NO}

\ifpourcent{123 % 456}{YES}{NO}
\end{document}

EDIT: sorry, I forgot to restore the catcode of % at the end :

\documentclass{minimal}
\usepackage{xstring}
\usepackage[T1]{fontenc}
\begingroup
\makeatletter
\catcode`\%12
\gdef\ifpourcent{\catcode`\%12\expandafter\relax\expandafter\ifpourcent@i\expandafter{\number\catcode`\% }}
\gdef\ifpourcent@i#1#2{\IfSubStr{#2}{%}{\catcode`\%#1 \@firstoftwo}{\catcode`\%#1 \@secondoftwo}}
\endgroup
\begin{document}
\ifpourcent{% tex1;}{YES}{NO}

\ifpourcent{abcd ef}{YES}{NO}

\ifpourcent{123 % 456}{YES}{NO}

% is still the comment char
\end{document}
unbonpetit
  • 6,190
  • 1
  • 20
  • 26
  • Thank you. This gets me a step closer to the goal! but somehow the % is not changed back to the comment char--where should I put \catcode`%=14? just before the endgroup? thanks again. – Tim A Oct 11 '11 at 18:35
  • thanks again--your edit now makes everything work. I must go and study it more since I understood it better before the edit! thanks again. I believe you send whatever the current catcode of % as the first argument of \ifpourcent@i. Is that in case someone has already changed it from a comment category to something else and you want to restore it to the original value, no matter what that is? – Tim A Oct 11 '11 at 19:12
  • What do you exactly want: that the catcode of % is restored to what it was before (see my edit above) or that it is forced to be 14 after the macro, whatever be its value before? – unbonpetit Oct 11 '11 at 20:10
  • You just answered my question--I was trying to understand the code. I see now, thanks. – Tim A Oct 11 '11 at 23:09