Replacing backslashes in a string with the ReplaceAll method in Java

Source: Internet
Author: User

Using the Java ReplaceAll method in the project today replaces the backslash ("\") in the string with an empty string (""), resulting in the following exception:

1 java.util.regex.PatternSyntaxException:Unexpected Internal Error near index 1 \^

Surf the internet for the wrong reason: in the regex "\ \" means a "\", in Java, a "\" also use "\ \" to indicate. In this way, the previous "\ \" represents "\" in the Regex, and the latter "\ \" represents "\" in Java. so to use the ReplaceAll method to replace the backslash ("\") in the string with an empty string (""), you need to write this: Str.replaceall ("\\\\", "");

Write a test code to demonstrate the exception that appears above:

1 String s= "C: \ Disk"; 2 s.replaceall ("\ \", "");

Using the code above will cause

1  Unexpected internal error near index 1 \^

To replace the "\" in the "C: \ Disk" With an empty string, the correct notation is

1  s.replaceall ("\\\\", "" ");

This will allow you to replace the normal.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.