字符串:将“(”替换为“\(”
我必须向 bash 发送一个字符串,其中包含转义序列。例如,我必须将“(”等特殊字符替换为“(”,因为bash会引发错误。我试过了,
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);
}
}
但没有运气。请帮助!!
谢谢
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!!
thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
String.replaceAll
使用正则表达式,这不是您想要的。只需使用String.replace
:String.replaceAll
uses a regular expression, which isn't what you want here. Just useString.replace
:发生这种情况是因为根据正则表达式语法(replaceAll 使用),( 是一个特殊字符。
在这种情况下,您应该采纳 Skeet 的建议并使用“replace”,但为了让您了解正则表达式版本的工作原理,这是一个固定的例子:
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:
查看所有正则表达式解决方案(String.replace(CharSequence, CharSequence) 也是正则表达式的实现),这里有一段代码在 Util 类之一中驻留了很长时间。 [这就是为什么它仍然使用 StringBuffer(旧时代)]
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)]