Take the 2-minute tour ×
TeX - LaTeX Stack Exchange is a question and answer site for users of TeX, LaTeX, ConTeXt, and related typesetting systems. It's 100% free, no registration required.

I have a variable that contains a long list of keywords, e.g.:

\keywords{computers, business, biology, fine art, literature, zoology}

I need to make an if-then statement that checks for the presence of a particular keyword, e.g.:

IF "zoology" IN keywords
THEN
    TRUE
ELSE
    FALSE

How can I check if a variable contains a particular keyword in plain TeX?

  • I can change the format of \keywords, e.g. \keywords{computers biology fine_art}, if that will be easier to implement.
share|improve this question
add comment

1 Answer

The following example uses package kvsetkeys to get a parser for lists with comma separated entries:

\input kvsetkeys.sty % parser for comma separated lists
\input ltxcmds.sty % helper macros

\catcode`\@=11 % \makeatletter
\newif\ifkey@found

% \testkeywordinlist{keyword}{keyword list}{true}{false}
\def\testkeywordinlist#1#2{%
  \edef\key@word{#1}%
  \edef\key@list{#2}%
  \key@foundfalse
  \expandafter\comma@parse\expandafter{\key@list}{%
    \ifx\comma@entry\key@word
      \key@foundtrue
      \comma@break
    \fi
    \ltx@gobble
  }%
  \ifkey@found
    \expandafter\ltx@firstoftwo
  \else
    \expandafter\ltx@secondoftwo
  \fi
}
\catcode`\@=12 % \makeatother

\def\keywords{computers, business, biology, fine art, literature, zoology}

\testkeywordinlist{zoology}{\keywords}{%
  \immediate\write16{* "zoology" found.}%
}{%
  \immediate\write16{* "zoology" not found.}%
}

\end

Result:

  • "zoology" found.
share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.