add tag
निरंजन
I am trying to count the number of instances of letter `a` from a given string delimited by a sequence `):`. For that I have the following non working code which gives an error message. How to solve this?

```
\documentclass{article}
\usepackage{xparse}
%% Courtesy: https://tex.stackexchange.com/a/525246
\ExplSyntaxOn
\NewDocumentCommand{ \mycount }{ s m m }{
  \IfBooleanTF { #1 }{
    \lng_count:nV { #2 } #3
  }{
    \lng_count:nn { #2 } { #3 }
  }
}
\cs_new_protected:Nn \lng_count:nn {
  \regex_count:nnN { #1 } { #2 } \l_tmpa_int
  \int_to_arabic:n { \l_tmpa_int }
}
\cs_generate_variant:Nn \lng_count:nn { n V }
\ExplSyntaxOff
\newcount\foo
\NewDocumentCommand{ \mycnt }{ u{):} }{%
  \foo=\numexpr\mycount{a}{#1}\relax
  #1%
}

\begin{document}
\mycnt aaaabccca ):
\end{document}
```

Also if I look at the output, it is exactly like I expect, but still the code is giving me this error. How to solve this?
Top Answer
Phelype Oleinik
`\mycount` is not expandable (because it uses `\regex_count:nnN`), so it can't appear in `\numexpr`.  When `\numexpr` starts, it is looking for a number, but then the first thing it sees is an unexpandable token, so it complains `Missing number, treated as zero`, which is exactly what happened: a number is missing for `\numexpr`, so it was treated as zero (thus `\foo` is zero).  Then the rest of the macro executes normally.

You need an expandable method to count the number of `a`, or first do the counting, then assign to `\foo`.

Here's a changed `\mycount` function that accepts a trailing optional argument, which should be a count register.  If the argument is provided, the count is assigned to that register, otherwise the count is typeset.

```
\documentclass{article}
\usepackage{xparse}
%% Courtesy: https://tex.stackexchange.com/a/525246
\ExplSyntaxOn
\int_new:N \l__lng_tmpa_int
\NewDocumentCommand \mycount { s m m o }
  {
    \IfBooleanTF {#1}
      { \lng_count:nVn {#2}  #3  {#4} }
      { \lng_count:nnn {#2} {#3} {#4} }
  }
\cs_new_protected:Nn \lng_count:nnn
  {
    \regex_count:nnN {#1} {#2} \l__lng_tmpa_int
    \IfValueTF {#3}
      { \int_set_eq:NN #3 \l__lng_tmpa_int }
      { \int_to_arabic:n { \l__lng_tmpa_int } }
  }
\cs_generate_variant:Nn \lng_count:nn { nV }
\ExplSyntaxOff

\newcount\foo
\NewDocumentCommand{ \mycnt }{ u{):} }{%
  \mycount{a}{#1}[\foo]
  \the\foo: #1%
}

\begin{document}
\mycnt aaaabccca ):
\end{document}
```

Enter question or answer id or url (and optionally further answer ids/urls from the same question) from

Separate each id/url with a space. No need to list your own answers; they will be imported automatically.