gurkensaas
gurkensaas

Reputation: 913

Check how many times a string is contained in a string in Applescript

So I want to set a variable (in this case numberOfContains) to the times that theString2 is contained in theString.

set theString to "hello world"
set theString2 to "l"
set numberOfContains to (times theString2 appears in theString) 
--This doesn't work, it's just a way of showing what I want my code to do
return numberOfContains --this should return 3

Upvotes: 0

Views: 330

Answers (2)

vadian
vadian

Reputation: 285240

Another way is Regular Expression

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

set theString to "hello world"
set theString2 to "l"
set regex to current application's NSRegularExpression's regularExpressionWithPattern:theString2 options:0 |error|:(missing value)
set numberOfContains to (regex's numberOfMatchesInString:theString options:0 range:{location:0, |length|:(count theString)}) as integer

Upvotes: 1

Reinhard Männer
Reinhard Männer

Reputation: 15247

I am not an Apple Script expert, but you could try the following:

set theString to "hello world"
set theString2 to "l"
set text item delimiters to theString2
set textItems to text items of theString
set nrOfTextItems to number of items of textItems
set numberOfContains to nrOfTextItems - 1  

numberOfContains will be 3.

Upvotes: 2

Related Questions