Reputation: 3270
I need to change a string as follow : Adding a "\" before any founded special character here an example : If the string = ${Name} the result should be ===> \${NAME}
I wrote this :
private static String getFormattedString(String variable) {
char [] specialCharacters = {'.', '\\', '+', '*', '?', '[', '^', ']', '$', '(', ')' ,'{' ,'}', '=', '!', '<', '>', '|', ':', '-'};
String old = variable;
String formatted = "";
int i=0;
while(i<old.length()) {
for (int j=0;j<specialCharacters.length;j++) {
if (old.charAt(i) == specialCharacters[j]) {
formatted+=old.substring(0, i)+"\\"+old.substring(i, i+1);
old=variable.substring(i+1,variable.length());
break;
}
}
i++;
}
return formatted;
}
But i'm getting a wrong result :
Formatted String : ++++> \${NAME\}
I'm really confused, any idea will be appreciated.
Upvotes: 1
Views: 243
Reputation: 121712
Try this:
private static final List<Character> SPECIAL = Arrays.asList('.', /* etc */);
public static String escape(final String input)
{
final StringBuilder sb = new StringBuilder(input.length());
final CharBuffer buf = CharBuffer.wrap(input);
char c;
while (buf.hasRemaining()) {
c = buf.get();
if (SPECIAL.contains(c))
sb.append('\\');
sb.append(c);
}
return sb.toString();
}
(CharBuffer
is underused, even though it is the best way to iterate over a String
's characters!)
If you use Guava 15+, you can also write your own CharEscaper
; like everything Guava, it works wonderfully well!
Upvotes: 4
Reputation: 774
Try to use replaceAll function
private static String getFormattedString(String variable) {
//No need this.
// char [] specialCharacters = {'.', '\\', '+', '*', '?', '[', '^', ']', '$', '(', ')' ,'{' ,'}', '=', '!', '<', '>', '|', ':', '-'};
variable = variable.replaceAll(".","\\."); //same for all.
variable = variable.replaceAll("+","\\+");.
variable = variable.replaceAll("*","\\*");
return formatted;
}
Upvotes: -2
Reputation: 6527
Try with String.replaceAll()
String strgg = "${Name}";
System.out.println(strgg.replaceAll("\\$", "\\\\\\$"));
Output:
\${Name}
Upvotes: 0
Reputation: 12122
If you just want to escape any special characters, try using StringEscapeUtils
from Apache Commons:
import org.apache.commons.lang.StringEscapeUtils;
(...)
String result = StringEscapeUtils.escapeJava(variable);
Upvotes: 1