Replace and replaceall

Source: Internet
Author: User

1) The replace parameter is Char and charsequence, which can be used to replace characters or strings (charsequence is the meaning of string sequence, which is a string in White );
2) The replaceall parameter is RegEx, that is, the replacement based on the Rule expression. For example, you can use replaceall ("\ D ","*") replace all numeric characters in a string with asterisks;

Replacefirst (), this method is also based on the Rule expression, but unlike replaceall (), it only replaces the string that appears for the first time;
In addition, if the parameters used by replaceall () and replacefirst () are not based on the Rule expression, the effect of replacing the string with Replace () is the same, both support string operations;
Note: After the replacement operation is executed, the content of the source string does not change.

Example:

String src = new string ("ab43a2c43d ");

System. Out. println (SRC. Replace ("3", "F"); => ab4f2c4fd.
System. Out. println (SRC. Replace ('3', 'F'); => ab4f2c4fd.
System. Out. println (SRC. replaceall ("\ D", "F"); => abffafcffd.
System. Out. println (SRC. replaceall ("A", "F"); => fb43fc23d.
System. Out. println (SRC. replacefirst ("\ D," F "); => abf32c43d
System. Out. println (SRC. replacefirst ("4", "H"); => abh32c43d.

How to replace "\" in a string "\\":

String msgin;
String msgout;
Msgout = msgin. replaceall ("\\\\","\\\\\\\\");
Cause:
'\' 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 the Escape Character in the regular expression (The replaceall parameter is the regular expression), and two must be used to represent one. Therefore, \\\\ is converted to \\\, \\by a regular expression \.
Similarly
Code :\\\\\\\\
Java :\\\\
RegEx :\\

Several Methods to replace '/' with '\' in a string:

Msgout = msgin. replaceall ("/","\\\\");
Msgout = msgin. Replace ("/","\\");
Msgout = msgin. Replace ('/','\\');

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.