tl;dr 对于>= OSX 10.8 的任何macOS 版本,您需要替换grep 的-P 选项(如 中所示)解决方案” 部分)与-E 选项 - 如本文底部的“不同的grep 实用程序”部分所述。
正如 cmets 中正确指出的那样...
Vanilla AppleScript 无法处理正则表达式。 - vadian
所以你需要
掏出一些知道正则表达式的东西 - red_menace
解决方案:
要以类似于 JavaScript 的 test() 方法的方式满足您对普通 AppleScript 的要求,请考虑使用自定义 AppleScript 子例程,如下所示:
子程序:
on regExpTest(str, re)
set statusCode to do shell script "grep -q -P " & quoted form of re & ¬
" <<<" & quoted form of str & " 2>/dev/null; echo $?"
if statusCode is equal to "0" then
return true
else
return false
end if
end regExpTest
用法:
set regExp to "\\d{5}"
set str to "This string contains 12345"
if regExpTest(str, regExp) then
display dialog "It DOES match so let's do something"
end if
运行上述脚本将显示一个带有给定消息的对话框,因为正则表达式和指定字符串之间存在匹配项。
注意: AppleScript 字符串使用反斜杠作为转义字符,因此您会注意到\d 元字符已通过额外的反斜杠进一步转义,即\\d
不等式运算符:
在 Javascript 中 != 没有。 applescript中的等价物是什么?以及如何处理正则表达式?
AppleScript 的 inequality operators 类似于 JavaScripts inequality operator (!=) 是:
≠
is not
isn't
isn't equal [to]
is not equal [to]
doesn't equal
does not equal
因此,鉴于您的 JavaScript if 声明:
if (!regEx.test(str)){
// do something
}
我们可以实现相同的逻辑,(再次使用前面提到的自定义regExpTest 子程序),使用以下代码:
set regExp to "\\d{5}"
set str to "This string contains 1234"
if regExpTest(str, regExp) ≠ true then
display dialog "It DOES NOT match so let's do something"
end if
注意str值只包含四个连续的数字,即1234。
这次运行上述脚本将显示一个对话框,其中包含给定消息,因为正则表达式和指定字符串之间存在 NOT 匹配项。
可以对上述 AppleScript if 语句进行许多变体,以实现相同的所需逻辑。例如;
if regExpTest(str, regExp) is not equal to true then
...
end if
if regExpTest(str, regExp) = false then
...
end if
等等……
regExpTest子程序解释:
前面提到的regExpTest AppleScript 子例程本质上是利用do shell script 命令来运行以下代码,您可以通过 macOS Terminal 应用程序直接运行这些代码。例如,在您的 Terminal 应用程序中运行以下两个命令:
grep -q -P "\d{5}" <<<"This string contains 12345" 2>/dev/null; echo $?
打印:
0
grep -q -P "\d{5}" <<<"This string contains 1234" 2>/dev/null; echo $?
打印:
1
编辑:不同的grep 实用程序:
正如user3439894 的评论中所指出的,Mac 上安装的grep 实用程序的某些版本似乎不支持-P 选项,该选项确保RegExp 模式被解释为Perl 正则表达式。我选择使用 Perl 正则表达式的原因是因为它们更接近于 JavaScript 中使用的正则表达式。
但是,如果您通过命令行运行 man grep 并发现您的 greputility 不提供 -P 选项,则在 regExpTest 子例程中更改以下代码行:
set statusCode to do shell script "grep -q -P " & quoted form of re & ¬
" <<<" & quoted form of str & " 2>/dev/null; echo $?"
改为:
set statusCode to do shell script "grep -q -E " & quoted form of re & ¬
" <<<" & quoted form of str & " 2>/dev/null; echo $?"
注意:-P 选项已更改为 -E,因此该模式现在被解释为扩展正则表达式 (ERE)。
速记元字符\d
您可能还发现需要将正则表达式模式的赋值从:
set regExp to "\\d{5}"
到
set regExp to "[0-9]{5}"
这次,速记元字符\d(用于匹配数字)已被替换为等效的字符类[0-9]。