AppleScript "if contain"

AppleScript "if contain"

我有一个脚本可以查找名称并搜索与另一个变量的匹配项。

它工作正常,但是如果变量 1 是 "Name Demo" 并且变量 2 是 "Demo Name",则脚本找不到匹配项。

set nameMatchTXT to ""
if NameOnDevice contains theName then
    set nameMatch to theName & " : Name Match"
end if

有什么办法可以改变这个来找到匹配的顺序吗? PS 脚本正在寻找单词通配符名称,有时处理双位字符可能会很困难。

您必须对每个条件进行单独检查。还有其他方法(例如复杂的正则表达式),但这是最简单和最易读的。

set nameMatch1 to "Name"
set nameMatch2 to "Demo"
if (NameOnDevice contains nameMatch1) and (NameOnDevice contains nameMatch2) then
    set nameMatch to NameOnDevice & " : Name Match"
end if

如果您要添加匹配条件,您最终可能会添加更多。您可能不想添加更多变量和更多条件,而是希望将所有单词放在一个列表中并进行检查。以后如果需要添加更多的单词,只需将单词添加到列表中即可。为了便于阅读,我在这里将它提取到一个单独的子例程中:

on name_matches(nameOnDevice)
    set match_words to {"Name", "Demo"}
    repeat with i from 1 to (count match_words)
        if nameOnDevice does not contain item i of match_words then
            return false
        end if
    end repeat
    return true
end name_matches


if name_matches(nameOnDevice) then
    set nameMatch to nameOnDevice & " : Name Match"
end if

澄清后编辑

如果您无法控制匹配的文本(如果它来自外部来源,并且不是您编码的),您可以将该文本拆分为单词并将其用作第二个示例中的单词列表。例如:

on name_matches(nameOnDevice, match_text)
    set match_words to words of match_text
    repeat with i from 1 to (count match_words)
        if nameOnDevice does not contain item i of match_words then
            return false
        end if
    end repeat
    return true
end name_matches


if name_matches(nameOnDevice, match_text_from_some_other_source) then
    set nameMatch to nameOnDevice & " : Name Match"
end if

您的要求如下:

if the variable 1 is "Name Demo" and variable 2 is "Demo Name" then the script don't find a match.

这将解决该问题:

set var1 to "Name Demo"
set var2 to "Demo Name"

if (var2 contains (word 1 of var1)) and (var2 contains (word 2 of var1)) then
    -- you have a match
    display dialog "var1 and var2 match"
else
    display dialog "no match"
end if