Sergey Shustikov
Sergey Shustikov

Reputation: 15821

Java replaceAll escape characters into double escape

I have a string value which received from input field.

String searchingText = getText();

After i receive a string i search this string. But if string contains \ symbol my search is failed.

I know about special characters and try to replace :

searchingText = searchingText.replaceAll("\\","\\\\");

But it give me error and app was shutdown.

Exception in thread "main" java.util.regex.PatternSyntaxException: Unexpected internal error near index 1

After research i founded a regex and try to replace with matcher :

    Map<String,String> sub = new HashMap<String,String>();
    sub.put("\n", "\\\\n");
    sub.put("\r", "\\\\r");
    sub.put("\t", "\\\\t");

    StringBuffer result = new StringBuffer();
    Pattern regex = Pattern.compile("\\n|\\r|\\t");
    Matcher matcher = regex.matcher(bodySearchText);

In the end i will want to get a string - searchingText = \\ instead of searchingText = \

Please any solutions.

Upvotes: 3

Views: 1398

Answers (2)

krishna
krishna

Reputation: 4089

change this

searchingText = searchingText.replaceAll("\\","\\\\");

to

searchingText = searchingText.replaceAll("\\\\","\\\\\\");

the replaceAll() will take \\ as \ .

for more details read here

Upvotes: 0

Maroun
Maroun

Reputation: 95978

You should do:

string = string.replaceAll("\\\\", "\\\\\\\\");

Note that in Java, \ is written as \\. So replaceAll will see \\ as \, which is not what you want.

Instead, you can use replace that accepts String and not a regex.

Upvotes: 2

Related Questions