Re: Number of occurrences of a character or string within a string
- Thanks for everyone's help, your suggestions work just fine in my code.
--- Antony Scriven <adscriven@...> wrote:
> On Jun 27, Tim Chase wrote:
> [I don't know who these are attributed to, sorry]
> > >>Is there a regular expression statement or a vim function to
> > >>return the number of a specific character or string within a
> > >>string?
> > >
> > >Take a look at
> > > :help count-items
> > [...]
> > The number of "s" or "t" characters, ignoring case:
> > strlen(substitute("This is a String", "[^st]", "","gi"))
> > or at least that last one *should* work. It's failing on my
> > vim6.0 here at work, even though doing a simple
> > :s/[^st]//gi
> > on a single line containing "This is a String" leaves 5
> > characters on the line, the above function returns 3 characters.
> > Bug?
> According to :help substitute(), only 'g' is a valid flag.
> Using \c in the regexp or switching on 'ignorecase' should
> > For a workaround, one could use
> > strlen(substitute("This is a String", "[^st]\\c", "","g"))
> Ah, you've done it! ( '[^st]\c' would also work.)
> > which properly returns "5"
> > Or, if you wanted to count things that *weren't* the letter "s"
> > or "t", then you could just remove the carat from the regexp.
> > Hope this gives some ideas,
> This following technique seems to work well for a multitude
> of things. For this case in particular it will allow you to
> count arbitrarily complex regexps.
> call substitute(str, pat, '\=SomeHelperFunction()', 'g')