如何在 mule 4 中转义“\”?

问题描述 投票:0回答:1

我有一个替换特殊字符的函数,但我无法跳过反斜杠

\
。我尝试将
{ searchValue: "\", replaceValue: "\\" } 
添加到 searchReplace 变量,但它不起作用。

功能如下:

%dw 2.0
output application/java

var searchReplace = [
        {
            searchValue: "?",
            replaceValue: "\?"
        },
        {
            searchValue: "&",
            replaceValue: "\&"
        },
        {
            searchValue: "|",
            replaceValue: "\|"
        },
        {
            searchValue: "!",
            replaceValue: "\!"
        },
        {
            searchValue: "^",
            replaceValue: "\^"
        },
        {
            searchValue: "~",
            replaceValue: "\~"
        },
        {
            searchValue: "*",
            replaceValue: "\*"
        },
        {
            searchValue: ":",
            replaceValue: "\:"
        },
        {
            searchValue: "+",
            replaceValue: "\+"
        },
        {
            searchValue: "'",
            replaceValue: "\'"
        },
        {
            searchValue: "-",
            replaceValue: "\-"
        },
        {
            searchValue: "{",
            replaceValue: "\{"
        },
        {
            searchValue: "}",
            replaceValue: "\}"
        },
        {
            searchValue: "[",
            replaceValue: "\["
        },
        {
            searchValue: "]",
            replaceValue: "\]"
        },
        {
            searchValue: "(",
            replaceValue: "\("
        },
        {
            searchValue: ")",
            replaceValue: "\)"
        }
]
fun replaceValuesArray(n,text,values) =
if (n == 0) text replace values[n].searchValue with(values[n].replaceValue) else replaceValuesArray(n - 1, text replace values[n].searchValue with(values[n].replaceValue), values)
var searchTerm = replaceValuesArray(sizeOf(searchReplace) - 1,payload.search, searchReplace)
---
if ((searchTerm == "") or (searchTerm == null)) "" else (searchTerm ++ "*")```
mule dataweave mulesoft mule4
1个回答
0
投票

如果我理解正确,您需要通过在输入字符串中的某些字符前添加反斜杠字符来转义这些字符。这可以通过 DataWeave 2.4 中的

mapString()
函数轻松完成。由于转义始终相同,因此我们不需要映射表。一个简单的要转义的特殊字符列表就足够了。

示例:

%dw 2.0
output application/java
var specialCharacters=["?", "&", "|", "[", "]", "\\"] // add characters as needed
---
payload dw::core::Strings::mapString 
    (if (specialCharacters contains ($)) "\\"++$ else $)

输入JSON(注意JSON需要输入反斜杠转义):

"this is \\a [test]"

输出Java字符串:

this is \\a \[test\]

mapString()
解决方案非常清楚表达的意图是什么。但是,如果您使用的是旧版本的 DataWeave 2,您可以通过替换使用
mapString()
将字符串拆分为字符数组,使用
map()
进行转换,然后将输出字符数组连接到又是一个字符串:

payload splitBy "" map (if (specialCharacters contains ($)) "\\"++$ else $) joinBy ""
© www.soinside.com 2019 - 2024. All rights reserved.