Replace and ReplaceAll are common substitution characters in Java
- Public string Replace (char OldChar, char Newchar) replaces the OldChar character with a newchar character in a string, returning a new string
- The public string replacealL (string regex,string replacement) replaces this string with the given replacement string to match each substring of the given regular expression.
Difference:
1) Replace parameter is char and charsequence, that is, can support the substitution of characters , also support the substitution of strings (charsequence is the meaning of the string sequence, in other words, the string);
2) The ReplaceAll parameter is the regex, which is based on the replacement of the regular expression , for example, can be ReplaceAll ("\\d", "*") all the numeric characters of a string are replaced by asterisks;
Same point:
Are all replacements, that is, the source string of a character or string is replaced by the specified character or string, if you want to replace only the first occurrence, you can use Replacefirst (), this method is based on the substitution of regular expressions, but unlike replaceall (), Replaces only the first occurrence of the string;
In addition, if the parameter data used by ReplaceAll () and Replacefirst () are not based on regular expressions, the effect of replacing the string with replace () is the same, that is, the operation of the string is also supported;
Also note: The contents of the source string have not changed since the substitution operation was performed.
Examples are as follows:
String src =NewString ("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 with "\ \":
String Msgin;
String msgout;
Msgout=msgin.replaceall ("\\\\","\\\\\\\\"
reason:' \ ' is an escape character in Java, so it takes two to represent one. For example, System.out.println ("\ \"); only one "\" is printed.
But ' \ ' is also an escape character in a regular expression (ReplaceAll's argument is a regular expression) and requires two to represent one. So:\\\\ is converted to \\,\\ by Java and converted to \ by the regular expression.
Same
CODE: \\\\\\\\
Java: \\\\
Regex: \ \
There are several ways to replace '/' in a string with ' \ ':
msgout= Msgin.replaceall ("/""\\\\");
msgout= msgin.replace ("/""\");
msgout= msgin.replace ('/'\ \'
Java Replace and ReplaceAll