Difference between replace and replaceall

Source: Internet
Author: User

Some of them are easy to mix up, so I will detail them here.

The replace parameters are char and charsequence, which can be used to replace characters or replace strings (charsequence is the meaning of string sequences, that is, strings );

The replaceall parameter is RegEx, that is, the replacement based on the Rule expression. For example, you can replaceall ("\ D", "*") to replace all the numeric characters of a string with asterisks;

Similarities: replace all characters with specified characters or strings;

Difference: replaceall supports regular expressions, so the parameter will be parsed (both parameters are), such as replaceall ("\ D", "*"), while replace does not, replace ("\ D", "*") is a string that replaces "\ D" and is not parsed as a regular expression.

There is another difference: "\" is an escape character in Java, so two must be used to represent one. For example, system. Out. println ("\"); only one "\" is printed "\". However, "\" is also an escape character in a regular expression and must be represented by two characters. Therefore, \\\\ is converted to \\\, \\ by a regular expression, so replaceall is replaced with "\" "\\", replaceall ("\\\\", "\\\\\\\\") is required, while Replace ("\\", "\\\\").

If you only want to replace the string that appears for the first time, you can use replacefirst (). This method is also based on the Rule expression, but unlike replaceall (), it only replaces the string that appears for the first time.

 

Speaking of regular expressions, there is an example to explain the use of replaceall. Replace Spaces

String test = "Wa n \ tg_p \ te \ tn G"; test = test. replaceall ("\ t | \ u0020 | \ u3000", ""); // remove the space system. out. println (test );

Where

test = test.replaceAll("\\t|\\\\t|\u0020|\\u3000", "")

And

test = Pattern.compile("\\t|\\\\t|\u0020|\\u3000").matcher(test).replaceAll("")

Is equivalent,

Therefore, replaceall or replacefirst can be used to replace all or the first regular expression.

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.