Count Substrings with AppleScriptObjC

Hey Folks,

I’ve got a means to find strings with a regular expression, but I’ve been looking the simplest and fastest method to count substrings with AppleScriptObjC and am falling flat…

TIA.

-Chris

Hi Chris, is this what you’re looking for?

use AppleScript version "2.4"
use framework "Foundation"
use scripting additions


set theText to "Praesent vel sapien lobortis dolor rhoncus congue eget quis ligula. Nulla nunc dolor, malesuada sit amet pharetra sit amet, dapibus eget felis. Mauris eget risus pellentesque, mattis arcu scelerisque, pellentesque metus. Cras maximus convallis tellus. Vivamus mollis nisi quis tincidunt semper. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Nullam sed nisl sapien. Aliquam consectetur tortor nisl, id interdum tortor consequat a."

set thePattern to "sapien"

set theString to current application's NSString's stringWithString:theText
set {theRegEx, theError} to current application's NSRegularExpression's regularExpressionWithPattern:(thePattern) options:0 |error|:(reference)
if theError ≠ missing value then error (theError's localizedDescription() as string)
set theCount to theRegEx's numberOfMatchesInString:(theString) options:0 range:{location:0, |length|:theString's |length|()}

Hey Pete,

I was thinking there was a simple string method, but this is more than good enough.

Thank you.

-Chris

1 Like

FWIW, there are a few NSString approaches that will work, although they are only marginally faster (0.2 millisecond) and the first approach lacks the flexibility of a regular expression in finding a match.

use framework "Foundation"

set theText to "Praesent vel sapien lobortis dolor rhoncus congue eget quis ligula. Nulla nunc dolor, malesuada sit amet pharetra sit amet, dapibus eget felis. Mauris eget risus pellentesque, mattis arcu scelerisque, pellentesque metus. Cras maximus convallis tellus. Vivamus mollis nisi quis tincidunt semper. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Nullam sed nisl sapien. Aliquam consectetur tortor nisl, id interdum tortor consequat a."
set theText to current application's NSString's stringWithString:theText
set thePattern to "sapien"

-- APPROACH ONE
set theArray to (theText's componentsSeparatedByString:thePattern)
set theCount to ((theArray's |count|()) - 1) --> 2

-- APPROACH TWO
set testText to theText's mutableCopy()
set theCount to (testText's replaceOccurrencesOfString:thePattern withString:"" options:1024 range:{0, testText's |length|()}) --> 2
1 Like