Mather class for Java Regex

Source: Internet
Author: User

Today in writing code, unit tests have a regular expression for a file directory replacement that was not passed in a Windows test.
Look at the original code as if there is no problem:
File F = new file ("D://1//1.txt");
String Source = "D://1";
String dest = "D://2";
String Absolutepath = F.getabsolutepath ();
String reg = Source;
String rep = dest;
String NewPath = Absolutepath.replaceall (Reg, Rep);
Expect Newpath:d://2//1.txt but still d://1//1.txt.

Looked at ReplaceAll's Javadoc, which had
Note this backslashes (/) and dollar signs ($) in the replacement string could cause the results to is different than if it were being treated as a literal replacement string; Seematcher.replaceall. Use Matcher.quotereplacement (java.lang.String) to suppress the special meaning of characters, if desired.

Suddenly suddenly enlightened.
To modify the code:
File F = new file ("D://1//1.txt");
String Source = "D://1";
String dest = "D://2";
String Absolutepath = F.getabsolutepath ();
String reg = matcher.quotereplacement (source);
String rep = matcher.quotereplacement (dest);
String NewPath = Absolutepath.replaceall (Reg, Rep);

Results Newpath:d://2//1.txt.

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.