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
Count occurrences in a string
Count occurrences in a string
Last edited by Papoulka on 10 Feb 2017 21:13, edited 1 time in total.
Re: Want: Count occurrences in a string
For your usecase:
?
Or am I missing something non-obvious here?
Code: Select all
$num = gettoken($P, "count", <crlf>);
Or am I missing something non-obvious here?
One of my scripts helped you out? Please donate via Paypal
Re: Want: Count occurrences in a string
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".
Thanks
EDIT: FYI, your gettoken code returns "3" when there are only two paths in the string; odd counter behavior. Gettokenindex returns "2".
Last edited by Papoulka on 10 Feb 2017 21:23, edited 1 time in total.
Re: Want: Count occurrences in a string
A general pattern count is done in the same way...
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...
Code: Select all
$num = gettoken(regexmatches($P, "<your pattern>"), "count", "|");
but it's so effortless to get the same result just with an additional gettoken()...
I'll move this thread to question and answers...
One of my scripts helped you out? Please donate via Paypal
Re: Count occurrences in a string
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
1. You didn't show the exact string, so how should I reply to this?EDIT: FYI, your gettoken code returns "3" when there are only two paths in the string; odd counter behavior. Gettokenindex returns "2".
2. Great that gettokenindex returns something different. May I now ask my crystal ball?
I can safely say that about cooking coffee (I guess)It's only effortless after you figure out how to do it
And gettoken() provides the count mechanism for (separated) strings. Following you logic formatlist() should have it's own countThat's why I'm asking for a direct count where folks would look first (regex or string functions).
as well?
One of my scripts helped you out? Please donate via Paypal