在Applescript中检查字符串包含多少次

在Applescript中检查字符串包含多少次,applescript,Applescript,因此,我想将一个变量(在本例中为numberOfContains)设置为字符串2包含在字符串中的时间 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 m

因此,我想将一个变量(在本例中为
numberOfContains
)设置为
字符串2
包含在
字符串中的时间

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

我不是苹果脚本专家,但您可以尝试以下方法:

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。

我不是苹果脚本专家,但您可以尝试以下方法:

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

另一种方法是正则表达式

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

由于“textItems”是一个列表,您可以使用“set nRoftTextItems to count of textItems”简化第5行-“length”也可以代替“count”。当然,您也可以通过在第5行添加“-1”来删除最后一行。@Mockman感谢您的评论,我将您的回答解释为删除第6行,并将第5行替换为
set numberOfContains to(number Of(items Of textItems))-1
set nrOfTextItems to(count Of textItems)-1
@Mockman将
数量的…
替换为
计数如何“简化”行?我认为,对于你所定义的更复杂的东西,你的门槛太低了<代码>数量…
可以(在本例中)。一种方法获取项目,然后对其进行计数。另一个只是计算列表。没有理由进入项目。由于“textItems”是一个列表,您可以使用“set nRoftTextItems to count of textItems”简化第5行-“length”也可以代替“count”。当然,您也可以通过在第5行添加“-1”来删除最后一行。@Mockman感谢您的评论,我将您的回答解释为删除第6行,并将第5行替换为
set numberOfContains to(number Of(items Of textItems))-1
set nrOfTextItems to(count Of textItems)-1
@Mockman将
数量的…
替换为
计数如何“简化”行?我认为,对于你所定义的更复杂的东西,你的门槛太低了<代码>数量…
可以(在本例中)。一种方法获取项目,然后对其进行计数。另一个只是计算列表。没有理由进入这些项目。