string: replace "(" with "\("
i have to send a string to the bash, which contains an escape sequence. For example, i have to replace special characters like "(" with "(", because the bash else throws errors. I trtied like
public class escape {
public static void main(String args[]) {
System.out.println("\\");
String s = "(foo)";
System.out.println(s);
s = s.replaceAll("(", "\\(");
System.out.println(s);
}
}
with no luck. Please help!!
thank开发者_如何学Cs
String.replaceAll
uses a regular expression, which isn't what you want here. Just use String.replace
:
s = s.replace("(", "\\(");
s = s.replaceAll("\\(", "\\\\(");
This is happening because the ( is a special character according to the regexp syntax (which is used by replaceAll).
You should take Skeet's advice and use "replace" instead in this case, but to give you an idea of how the regexp version works, here's a fixed example:
public class test {
public static void main(String args[]) {
System.out.println("\\");
String s = "(foo)";
System.out.println(s);
s = s.replaceAll("\\(", "\\\\(");
System.out.println(s);
}
}
Looking at all regexp solutions (String.replace(CharSequence, CharSequence) is also regexp impl. under the hoold), here a piece of code residing for ages in one of the Util classes. [This is why it still uses StringBuffer (old times)]
public static String replace(String strToRepl,String orig,String repl){
if (strToRepl==null) return null;
int len=strToRepl.length();
StringBuffer buf=null;
int ind;
int origLen=orig.length();
int start=0;
while (start<len&&(ind=strToRepl.indexOf(orig,start))>=0){
if (buf==null) buf=new StringBuffer(len*3/2);
buf.append(strToRepl.substring(start,ind)).append(repl);
start=origLen+ind;
}
if (buf!=null){
if (start<len)
buf.append(strToRepl.substring(start));
return buf.toString();
}
return strToRepl;
}
精彩评论