'How to replace "<space>" with "\\<space>" in groovy

Tried with

def resultString="Hello word result Hello: 0 Word: 0 void: 0"
def resultString1=resultString.replaceAll(' ', '\\\\ ')
println resultString1

Expected Result:

Hello\\ word\\ result\\ Hello:\\ 0\\ Word:\\ 0\\ void:\\ 0

Actual Getting:

Hello\ word\ result\ Hello:\ 0\ Word:\ 0\ void:\ 0

Any input will be very useful



Solution 1:[1]

def resultString="Hello word result Hello: 0 Word: 0 void: 0" println(resultString.replaceAll("\\s","\\\\\\\\"))

Solution 2:[2]

https://docs.oracle.com/javase/8/docs/api/java/lang/String.html#replaceAll-java.lang.String-java.lang.String-
replaceAll uses Regex Matching, which changes the behaviour of the escaping

use replace instead:

def resultString="Hello word result Hello: 0 Word: 0 void: 0"
def resultString1=resultString.replace(' ','\\\\')
println resultString1

output:

Hello\\word\\result\\Hello:\\0\\Word:\\0\\void:\\0

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Humble Bee
Solution 2 Raildex