0

I have a string like s = "abc\def" and I want to replace "" with "/" and makes the string like "abc/def/".

I tried replaceAll("\\","/") but the compiler is giving error for string

error: illegal escape character String s="abc\def";

Konrad Rudolph
  • 530,221
  • 131
  • 937
  • 1,214
  • 1
    If you're defining a string literal you need to escape the backslash there as well: `String s = "abc\\def"`. Then, since `replaceAll()` takes a regex, you need to escape the backslash in the regex too and since the regex would be added as a literal you'd need double escaping: `replaceAll("\\\\", "/")` (`"\\\\"` to get the regex ``\\``). – Thomas Mar 25 '22 at 09:00
  • but the thing is I can't change the string. The data is fetched from an excel sheet and I need the string in "abc/def/" format but currently it's in "abc\def\" format. – MUSKAN RANI Mar 25 '22 at 09:05
  • @MUSKANRANI If the string was fetched from an Excel sheet, you wouldn’t be getting the error message that you posted. That error message *specifically* refers to a literal string in your Java code. – Konrad Rudolph Mar 25 '22 at 09:07
  • Yes Konrad I am getting this error because after fetching the data from excel I am storing it in String and then doing the process. String s = row.getCell(3).getStringCellValue(); // Like this – MUSKAN RANI Mar 25 '22 at 09:10
  • `String s = row.getCell(3).getStringCellValue();` cannot result in `illegal escape character String s="abc\def";`. That message specifically refers to literals and it already states the literal you've used, i.e. `"abc\def"`. Thus that error probably only occurs in your test code while your actual code probably results in a `PatternSyntaxException` due to the missing regex-escape of the backslash. – Thomas Mar 25 '22 at 09:25
  • Yes correct, Actually previously I was using replaceAll() and now I tried with replace, it is working fine. Thanks – MUSKAN RANI Mar 25 '22 at 09:30

1 Answers1

1

The issue is that Java uses \ as the string escape character, but also as the regex escape character, and replaceAll performs a regex search. So you need to doubly escape the backslash (once to make it a literal \ in the string, and once to make it a literal character in the regular expression):

result = str.replaceAll("\\\\", "/");

Alternatively, you don’t actually need regular expressions here, so the following works as well:

result = str.replace("\\", "/");

Or, indeed, using the single-char replacement version:

result = str.replace('\\', '/');
Konrad Rudolph
  • 530,221
  • 131
  • 937
  • 1,214
  • You are correct, but the error is on the string `"abc\def"` because `\d` is not a valid escape sequence. – seenukarthi Mar 25 '22 at 09:01
  • 1
    @KarthikeyanVaithilingam You’re right, I had missed that. However, OP has now clarified that the error message is actually unrelated to the *actual* issue. – Konrad Rudolph Mar 25 '22 at 09:45