String.replaceAll 带有双反斜杠的单反斜杠 [英] String.replaceAll single backslashes with double backslashes

查看:51
本文介绍了String.replaceAll 带有双反斜杠的单反斜杠的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将 String something 转换为 String \something\使用 replaceAll,但我不断收到各种错误.我认为这是解决方案:

I'm trying to convert the String something into the String \something\ using replaceAll, but I keep getting all kinds of errors. I thought this was the solution:

theString.replaceAll("\", "\\");

但这给出了以下例外:

java.util.regex.PatternSyntaxException: Unexpected internal error near index 1

推荐答案

String#replaceAll() 将参数解释为 正则表达式. Stringregex 中的转义字符.您需要为正则表达式双重转义它:

The String#replaceAll() interprets the argument as a regular expression. The is an escape character in both String and regex. You need to double-escape it for regex:

string.replaceAll("\\", "\\\\");

但是您不一定需要为此使用正则表达式,仅仅是因为您想要一个逐个字符的精确替换,并且您不需要这里的模式.所以 String#replace() 应该足够了:

But you don't necessarily need regex for this, simply because you want an exact character-by-character replacement and you don't need patterns here. So String#replace() should suffice:

string.replace("\", "\\");

<小时>

更新:根据评论,您似乎想在 JavaScript 上下文中使用该字符串.您可能最好使用 StringEscapeUtils#escapeEcmaScript() 来覆盖更多字符.


Update: as per the comments, you appear to want to use the string in JavaScript context. You'd perhaps better use StringEscapeUtils#escapeEcmaScript() instead to cover more characters.

这篇关于String.replaceAll 带有双反斜杠的单反斜杠的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆