user2630355
user2630355

Reputation: 9

Replacing backslash by another symbol in escape symbol

I have string some_text\1\12\3. Need to get string some_text.1.12.3, i. e. replace \ by .. The problem is that Java interprets \1 as one symbol (escape-symbol). And actually I need to replace part of escape-symbol.

Upvotes: 0

Views: 96

Answers (2)

Jon Skeet
Jon Skeet

Reputation: 1503110

It sounds like all you're missing is the knowledge of how to escape the backslash in a Java string literal - which is a matter of doubling the backslash:

String replaced = original.replace('\\', '.');

On the other hand, it's not clear where your text is coming from or going to anyway - the \1 part would only be relevant if it's being processed as part of a text literal. If you're actually trying to create a string of "some_text\1\12\3" in Java source code to start with, you'd want:

String withBackslashes = "some_text\\1\\12\\3";

Note that the actual text of the string that withBackslashes refers to only has three backslashes, not six. It's only the source code that needs them doubling. At that point, the replacement code at the top would replace the backslashes with dots.

Upvotes: 10

jlordo
jlordo

Reputation: 37833

This will do the job:

str = str.replace('\\', '.');

Upvotes: 5

Related Questions