Skip to content

Commit

Permalink
Support for replace with regexp
Browse files Browse the repository at this point in the history
This PR addresses issues schibsted#346 and schibsted#347.
  • Loading branch information
Carlo Dapor committed May 26, 2024
1 parent 0cdb65a commit 22aaa35
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,7 @@ public class BuiltinFunctions {
functions.put("from-json", new BuiltinFunctions.FromJson());
functions.put("to-json", new BuiltinFunctions.ToJson());
functions.put("replace", new BuiltinFunctions.Replace());
functions.put("replace-regexp", new BuiltinFunctions.ReplaceRegexp());
functions.put("trim", new BuiltinFunctions.Trim());
functions.put("uuid", new BuiltinFunctions.Uuid());

Expand Down Expand Up @@ -961,6 +962,32 @@ else if (pos < string.length())
}
}

// ===== REPLACE-REGEXP

public static class ReplaceRegexp extends AbstractRegexpFunction {

public ReplaceRegexp() {
super("replace-regexp", 3, 3);
}

public JsonNode call(JsonNode input, JsonNode[] arguments) {
int args = null == arguments ? 0 : arguments.length;
if (args != 3) {
throw new JsltException("ReplaceRegexp requires 3 arguments, only " + args + " provided!");
}

String string = NodeUtils.toString(arguments[0], true);
if (string == null)
return NullNode.instance;

String regexp = NodeUtils.toString(arguments[1], false);
String replacement = NodeUtils.toString(arguments[2], false);
String result = !string.matches(regexp) ? string : string.replaceAll(regexp, replacement);

return new TextNode(result);
}
}

// ===== TRIM

public static class Trim extends AbstractFunction {
Expand Down
10 changes: 10 additions & 0 deletions core/src/test/resources/function-tests.json
Original file line number Diff line number Diff line change
Expand Up @@ -1127,6 +1127,16 @@
"input" : "\"some text\"",
"output": "\"\""
},
{
"query": "replace-regexp(., \"([0-9][0-9][0-9][0-9])-([0-9][0-9])-([0-9][0-9])\", \"$2/$3/$1\")",
"input" : "\"2019-12-31\"",
"output": "\"12/31/2019\""
},
{
"query": "replace-regexp(., \"(?<year>[0-9][0-9][0-9][0-9])-(?<month>[0-9][0-9])-(?<day>[0-9][0-9])\", \"${day}.${month}.${year}\")",
"input" : "\"2019-12-31\"",
"output": "\"31.12.2019\""
},
{
"query": "trim(.)",
"input" : "\"some text\"",
Expand Down

0 comments on commit 22aaa35

Please sign in to comment.