【问题标题】:AppleScript "if contain"AppleScript“如果包含”
【发布时间】:2017-10-02 12:01:53
【问题描述】:

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

它工作正常,但是如果变量 1 是“名称演示”并且变量 2 是“演示名称”,那么脚本找不到匹配项。

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

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

【问题讨论】:

    标签: if-statement applescript contain


    【解决方案1】:

    您的要求:

    如果变量 1 是“名称 Demo”,变量 2 是“演示名称”,那么 脚本找不到匹配项。

    这将解决这个问题:

    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
    

    【讨论】:

    • 唯一的问题是我有时会遇到此错误“错误“无法将 \"\" 的第 1 个单词转换为 Unicode 文本类型。"从 "" 的第 1 个单词到 Unicode 文本的数字 -1700"
    【解决方案2】:

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

    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
    

    【讨论】:

    • 谢谢你的回复,问题是,实际的名字变量是自动取自另一个脚本的,基本上是把全名放在一起
    猜你喜欢
    • 2016-12-14
    • 2017-03-25
    • 1970-01-01
    • 1970-01-01
    • 2013-12-03
    • 1970-01-01
    • 2013-01-08
    • 2012-01-07
    • 2013-10-27
    相关资源
    最近更新 更多