检查一个字符串在 Applescript 中的字符串中包含了多少次

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

所以我想将一个变量(在本例中为 numberOfContains)设置为 theString2 包含在 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

我不是 Apple Script 专家,但您可以尝试以下方法:

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 将是 3.

另一种方式是正则表达式

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