AppleScript检测字符串含指定文本返回值不稳定,如何判断姓名是单人/双人
问题根因
- 你代码里的问题出在
some text item of coupleIdentifiers这个写法:AppleScript中some关键字的作用是随机选取集合中的任意一个元素,不是你以为的“存在任意一个匹配项”。所以每次运行时会随机从数组里挑一个标识符做匹配,自然会出现结果随机波动的情况。
AppleScript修复方案
不要用some,改为遍历所有标识符逐一判断,只要有一个匹配就返回true,示例代码如下:
set x to "John Jacob & Johanna Smith" set y to "Kathy and Kurt Gallows" set z to "Barbara Southerland" set theName to z -- 可替换为x/y测试 set coupleIdentifiers to {"&", " and "} set testIt to false repeat with identifier in coupleIdentifiers if theName contains identifier then set testIt to true exit repeat -- 匹配到就提前退出,无需继续判断 end if end repeat get testIt
该版本运行结果稳定,x、y返回true,z返回false,符合你的需求。
JavaScript备选实现方案
如果你要切换到JavaScript for Automation(JXA,Apple平台原生支持的JS自动化脚本),实现逻辑更直观:
const x = "John Jacob & Johanna Smith" const y = "Kathy and Kurt Gallows" const z = "Barbara Southerland" const theName = x const coupleIdentifiers = ["&", " and "] const testIt = coupleIdentifiers.some(id => theName.includes(id)) console.log(testIt)
直接用数组的some方法,语义就是“存在任意一个匹配项”,完全符合你最初的逻辑预期。
内容的提问来源于stack exchange,提问作者RCR88
相关产品推荐
相关产品推荐

