了解匹配运算符

时间:2019-03-21 06:05:39

标签: mule dataweave

嗨,我对match运算符的用法感到困惑。我遇到了一段代码,看起来像文档中的解释一样:https://docs.mulesoft.com/mule-runtime/3.9/dataweave-operators#match

%function testMatch(key)
    (key match {
        x when x is :null -> false,
        x when x == "A" -> true, 
        x when x == "B" -> false, 
        x when x == "J" -> true, 
        x when x == "K" -> false, 
        x when x == "L" -> true, 
        default -> false
    })

请帮助理解该匹配语法的含义

1 个答案:

答案 0 :(得分:2)

好问题! match关键字在DataWeave中有两个作用,取决于关键字的位置。 Match用于正则表达式或模式匹配。


match for Regex

如果match在左侧(lhs)有一个字符串,在rhs上有一个正则表达式,则它将根据以下docs进行操作。基本上,它正在做正则表达式匹配:

  

Match返回一个包含整个匹配表达式的数组,然后是与提供的正则表达式匹配的所有捕获组。


match用于模式匹配

如果match在lhs上具有任何值(即不对函数求值),而在rhs上具有空心括号,则match现在正在进行模式匹配。您可以找到该here的文档。我在我的演讲中对此进行了广泛的介绍,您可以找到该here的幻灯片。

对于您提供的示例(不错的格式,顺便说一句):

%function testMatch(key)
    (key match {
        x when x is :null -> false,
        x when x == "A" -> true, 
        x when x == "B" -> false, 
        x when x == "J" -> true, 
        x when x == "K" -> false, 
        x when x == "L" -> true, 
        default -> false
    })

match正在检查其输入x是否为null,A,B,J,K或L。如果与它们中的任何一个匹配,DW将评估正在执行的操作箭头的rhs,然后立即返回。如果没有匹配项,它将返回default箭头的rhs。