Replace first and last occurrence of a string with another

126 Views Asked by At

Given a string "[ something that may contain a brace ], like so]". The start and end brackets need to be replaced with ( and ) or alternatively removed. I am really looking for the replacement and not the removal. Braces on the inside of the string need to remain

The default given by AppSync is as follows:

#set( $valStr = $vals.toString().replace("[","(").replace("]",")") )

Can anyone help to to do this with one line.

The code above would make the mentioned string "( something that may contain a brace ), like so)"

What I need is:

"( something that may contain a brace ], like so)"

1

There are 1 best solutions below

1
Vale On

I think there´s only a workaround for this problem. You can use replaceFirst after you replaced all square brackets: #set($vals = "[ something that may contain a brace ], like so]") #set( $valStr = $vals.toString().replace("[","(").replace("]",")") ) $valStr.replaceFirst(")","]"))