如何更换“ ”与“ ”在java中

发布于 2024-12-06 06:21:07 字数 155 浏览 0 评论 0原文

我尝试将字符串分解为数组并将 \ 替换为 \\ ,但无法做到这一点,我也尝试了 String.replaceAll 类似这样的 (" \","\\");

我想提供 JNI 的路径,它只能以这种方式读取。

I tried to break the string into arrays and replace \ with \\ , but couldn't do it, also I tried String.replaceAll something like this ("\","\\");.

I want to supply a path to JNI and it reads only in this way.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

胡渣熟男 2024-12-13 06:21:07

不要使用 String.replaceAll 在这种情况下 - 这是根据正则表达式指定的,这意味着您需要更多转义。这应该没问题:

String escaped = original.replace("\\", "\\\\");

请注意,由于 Java 字符串文字中的反斜杠是双反斜杠 - 因此这里涉及的实际字符串是“单反斜杠”和“双反斜杠”-而不是双反斜杠和四重反斜杠。

< code>replace 适用于简单字符串 - 不涉及正则表达式。

Don't use String.replaceAll in this case - that's specified in terms of regular expressions, which means you'd need even more escaping. This should be fine:

String escaped = original.replace("\\", "\\\\");

Note that the backslashes are doubled due to being in Java string literals - so the actual strings involved here are "single backslash" and "double backslash" - not double and quadruple.

replace works on simple strings - no regexes involved.

请叫√我孤独 2024-12-13 06:21:07

您可以使用 replaceAll

String escaped = original.replaceAll("\\\\", "\\\\\\\\");

You could use replaceAll:

String escaped = original.replaceAll("\\\\", "\\\\\\\\");
摇划花蜜的午后 2024-12-13 06:21:07

我想提供 JNI 的路径,它只能以这种方式读取。

那是不对的。您只需要在用编程语言声明的文字字符串中使用双反斜杠。您永远不必在运行时进行此替换。你需要重新思考为什么要这样做。

I want to supply a path to JNI and it reads only in this way.

That's not right. You only need double backslashes in literal strings that you declare in a programming language. You never have to do this substitution at runtime. You need to rethink why you're doing this.

远山浅 2024-12-13 06:21:07

处理“\”可能是一个相当冒险的事情,因为它在 Java 中被视为转义字符。您总是需要在字符串中使用“\”来表示“\”。但是当您想在正则表达式中使用“\”时,乐趣就开始了,因为“\”也是正则表达式中的转义字符。因此,对于单个“\”,您需要在正则表达式中使用“\\”。

这是我找到此信息的链接: https://www.rgagnon.com/ javadetails/java-0476.html

我必须将 '\' 转换为 '\\'。我找到了我们可以使用的地方:

filepathtext = filepathtext.replace("\\","\\\\"); 

并且它有效。
下面给出的是我如何实现它的图像。

https://i.sstatic.net/LVjk6.png

It can be quite an adventure to deal with the "\" since it is considered as an escape character in Java. You always need to "\" a "\" in a String. But the fun begins when you want to use a "\" in regex expression, because the "\" is an escape character in regex too. So for a single "\" you need to use "\\" in a regex expression.

here is the link where i found this information: https://www.rgagnon.com/javadetails/java-0476.html

I had to convert '\' to '\\'. I found somewhere that we can use:

filepathtext = filepathtext.replace("\\","\\\\"); 

and it works.
Given below is the image of how I implemented it.

https://i.sstatic.net/LVjk6.png

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文