Java String replace

Posted on 2008-10-01
Last Modified: 2012-06-22
If a string contains \\\\ (4 backslashes) is there anyway to replace that string with \ (one backslash)?
Tried the following:
strtest.replace("\\\\", "\") - unclosed String literal error
strtest.replace("\\\\", "\\") - hoped it would see the first back slash as an escape but replaces with 2 \\

Thanks for any ideas.
Question by:edwardui
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 2

Expert Comment

ID: 22619658
You have to understand that:

"\\"  --> means "\"

Backslash is a special character, so doing this:

"\"  is incorrect syntax... Change it to "\\"

Or, use the @ sign before the quotation, then it is ok for you to not need to use double backslashes

@"\"  is ok

Accepted Solution

mbodewes earned 500 total points
ID: 22619661
Backslash is an escape character, this should work:

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

So you've got 4 escaped backslashes, replaced by a single escaped backslash (!).

Expert Comment

ID: 22619695
strtest.replace(@"\\\\", @"\");

Author Comment

ID: 22619967
Thank you for the replies.  
strtest.replace("\\\\\\\\", "\\"); was what i was looking for.
I don't think @ works in java.  Think i remember using that in .NET though

Featured Post

Free Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
servlet example 11 77
Facing this issue for maven proxy setting 2 45
Bot application - advice 3 81
What does this method description mean? 1 17
INTRODUCTION Working with files is a moderately common task in Java.  For most projects hard coding the file names, using parameters in configuration files, or using command-line arguments is sufficient.   However, when your application has vi…
After being asked a question last year, I went into one of my moods where I did some research and code just for the fun and learning of it all.  Subsequently, from this journey, I put together this article on "Range Searching Using Visual Basic.NET …
Viewers will learn about the regular for loop in Java and how to use it. Definition: Break the for loop down into 3 parts: Syntax when using for loops: Example using a for loop:
This theoretical tutorial explains exceptions, reasons for exceptions, different categories of exception and exception hierarchy.
Suggested Courses

752 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question