Search code examples
regexvelocityaws-appsyncvtl

Is it possible to perform regex based string replacement inside a VTL resolver?


I want to define a Response Mapping Template as follows:

#set( $postIds = [] )
#foreach( $item in $ctx.result.items )
    #if( !$util.isNull($item))
        $util.qr($postIds.add($item.SK.replace("^([0-9]){1,}-", "")))
    #end
#end

{
    "items": $utils.toJson($postIds),
    #if( ${context.result.nextToken} )
    "nextToken": "${context.result.nextToken}",
    #end
}

The goal is to remove a timestamp followed by a "-" character at the beginning of the SK property of every item.

I checked that the Regex was correct, but this does not seem to work because the digits at the beginning are not removed.

Also tried with ...replace(/^([0-9]){1,}-/", "").

If I remember correclty, the documentation says somewhere that all Java string methods are available.

What am i doing incorrectly here ?


Solution

  • To replace regex use replaceAll

    Replaces each substring of this string that matches the given regular expression with the given replacement.

    Or replaceFirst

    Make sure SK is String or use toString()