How do I replace the a portion of the string with special characters

I would like to replace a certain portion of the string with "\\_\\_\\_\\_\\_"

(e.g. String str = "Hello World")

If I do str.replaceAll("World", "\\_\\_\\_\\_\\_");

I don't see the "\" character in my replaced string, I would expect it to show me "Hello \_\_\_\_\_"

Answers


You need:

str = str.replaceAll("World", "\\\\_\\\\_\\\\_\\\\_\\\\_");

See it.

\ is the escape character in Java strings. So to mean a literal \ you need to escape it with another \ as \\.

\ is the escape char for the regex engine as-well. So a \\ in Java string will be sent to regex engine as \ which is not treated literally but instead will be used to escape the following character.

To pass \\ to regex engine you need to have \\\\ in the Java string.


Since you are replacing a string (not pattern) with another string, there is really no need for regex, you can use the replace method of the String class as:

input = input.replace("World", "\\_\\_\\_\\_\\_");

See it.


Need Your Help

BroadcastReceiver: set android:process programmatically

android broadcastreceiver storage

I want my app to detect if when the state of external storage changes. At first defined a BroadcastReceiver in my AndroidManifest. Here I can set android:process and android:exported attributes like

How to separate CUDA code into multiple files

c++ c visual-studio-2008 cuda

I am trying separate a CUDA program into two separate .cu files in effort to edge closer to writing a real app in C++. I have a simple little program that: