Java:replaceAll在反斜杠上不能很好地工作吗? [英] Java: replaceAll doesn't work well with backslash?

查看:37
本文介绍了Java:replaceAll在反斜杠上不能很好地工作吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将反斜杠替换为其他字符串.由于某些奇怪的原因,replaceAll函数不喜欢反斜杠.

I'm trying to replace the beginning of a string with backslashes to something else. For some weird reason the replaceAll function doesn't like backslashes.

String jarPath = "\\\\xyz\\abc\\wtf\\lame\\";
jarPath = jarPath.replaceAll("\\\\xyz\\abc", "z:");

我应该怎么做才能解决这个问题.

What should I do to solve this issue.

谢谢.

推荐答案

您需要将每个反斜杠加倍(再次),因为replaceAll()使用的Pattern类将其视为特殊字符:

You need to double each backslash (again) as the Pattern class that is used by replaceAll() treats it as a special character:

String jarPath = "\\\\xyz\\abc\\wtf\\lame\\";
jarPath = jarPath.replaceAll("\\\\\\\\xyz\\\\abc", "z:");

Java字符串将反斜杠视为转义字符,因此replaceAll看到的是: \\\\ xyz \\ abc .但是replaceAll还将反斜杠视为转义字符,因此正则表达式成为以下字符: \ \ x y z \ a b c

A Java string treats backslash as an escape character so what replaceAll sees is: \\\\xyz\\abc. But replaceAll also treats backslash as an escape character so the regular expression becomes the characters: \ \ x y z \ a b c

这篇关于Java:replaceAll在反斜杠上不能很好地工作吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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