substitution function for string strings in Java: The difference between replace and ReplaceAll

Source: Internet
Author: User

For example, a string with the following X

String x = "[Kllkklk\\kk\\kllkk]";
To replace the "KK" inside with + +, you can use both methods to get the same result

Replace (charsequence target, charsequence replacement)--x.replace ("KK", "+ +")

ReplaceAll (string regex, string replacement)--x.replaceall ("KK", "+ +")

There is no difference between the two functions, and the following "\ \" In the string is replaced with "+ +"
System.out.println (x.replace ("\ \", "+ +")); No problem
System.out.println (X.replaceall ("\ \", "+ +")); Error java.util.regex.PatternSyntaxException

It can be seen that there is a difference when replacing with an escape character. The ReplaceAll parameter is the regex, which is the regular expression. First, it will be escaped, so error.

If you use System.out.println (X.replaceall ("\\\\", "+ +"), you are done.

So what is the choice of the function when using normal string substitution?

String x = "[Kllkklk\\kk\\kllkk]";
String tmp;
System.out.println (X.replace ("[", "#"). Replace ("]", "#");
System.out.println (New Date (). GetTime ());
for (int i =0;i<1000000;i++)
Tmp=x.replace ("KK", "--");
System.out.println (New Date (). GetTime ());
for (int i =0;i<1000000;i++)
Tmp=x.replaceall ("KK", "+ +");
System.out.println (New Date (). GetTime ());

Test results:

1312424571937
1312424574531
1312424576671

It is faster to test the ReplaceAll function. See source found, replace function inside still use ReplaceAll function.

General principle: The Replace function is recommended when a string cannot determine whether an escape character is available and does not need to be escaped

Otherwise, use the ReplaceAll function

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.