Page 1 of 1

Count occurrences in a string

Posted: 10 Feb 2017 21:01
by Papoulka
I've wanted this several times; somehow got by without, so tell me if I'm missing something obvious...

--> I want to count how many times a pattern occurs in a string.

I suggest a flag on some existing function (regexmatches or strpos seem likely) to do this. AFAIK only gettokenindex has anything like this now, and its use with patterns is limited to the '*' wildcard. A count feature on regexmatches would be very nice.

Thx

Re: Want: Count occurrences in a string

Posted: 10 Feb 2017 21:11
by highend
For your usecase:

Code: Select all

$num = gettoken($P, "count", <crlf>);
?

Or am I missing something non-obvious here?

Re: Want: Count occurrences in a string

Posted: 10 Feb 2017 21:16
by Papoulka
Sorry highend - I had a brainwave right after posting and edited mine - but you replied even faster. I did miss "gettoken" in this case, and I did make "gettokenindex" do it with a wildcard. I think it's still worth asking for a pattern count, especially with regex.

Thanks

EDIT: FYI, your gettoken code returns "3" when there are only two paths in the string; odd counter behavior. Gettokenindex returns "2".

Re: Want: Count occurrences in a string

Posted: 10 Feb 2017 21:23
by highend
A general pattern count is done in the same way...

Code: Select all

$num = gettoken(regexmatches($P, "<your pattern>"), "count", "|");
I know other languages provide a count inside a regexmatch function by default
but it's so effortless to get the same result just with an additional gettoken()...

I'll move this thread to question and answers...

Re: Count occurrences in a string

Posted: 10 Feb 2017 21:26
by Papoulka
It's only effortless after you figure out how to do it. That's why I'm asking for a direct count where folks would look first (regex or string functions).

Re: Count occurrences in a string

Posted: 10 Feb 2017 21:37
by highend
EDIT: FYI, your gettoken code returns "3" when there are only two paths in the string; odd counter behavior. Gettokenindex returns "2".
1. You didn't show the exact string, so how should I reply to this?
2. Great that gettokenindex returns something different. May I now ask my crystal ball?
It's only effortless after you figure out how to do it
I can safely say that about cooking coffee (I guess) :ninja:
That's why I'm asking for a direct count where folks would look first (regex or string functions).
And gettoken() provides the count mechanism for (separated) strings. Following you logic formatlist() should have it's own count
as well?