Differences between string. Replace () and string. replaceall () in Java and their usage |
At first glance, it literally seems that replace only replaces the first character (affected by JavaScript). replaceall replaces all the characters. In fact, it is not big, but it is used differently. Please send an email to the freeget.one@gmail.com for strong software. Public String Replace (char oldchar, char newchar) Returns a new string generated by replacing all the oldchar in the string with newchar. If oldchar does not appear in the Character Sequence represented by this string object, a reference to this string object is returned. Otherwise, a New String object is created to represent the Character Sequence equal to the Character Sequence represented by this string object, except that each oldchar that appears is replaced by a newchar.Public String replaceall (string RegEx, string replacement) replaces this string with the given replacement string to match each substring of the given regular expression. The Str. replaceall (RegEx, REPL) method called by this method produces results identical to the following expressions: Pattern. Compile (RegEx). matcher (STR). replaceall (repl) Parameters: RegEx-Regular Expression used to match this string Return Value: String Throw: patternsyntaxexception-if the regular expression syntax is invalid. Practical application: Public static void main (string [] Arg) throws ognlexception { String S = "SDF // A // AA "; // Replace the backslash/in S // System. Out. println (s ); System. Out. println (S. replaceall ("////","////////")); System. Out. println (S. Replace ("//","////")); } We can see that the above two return the same replacement result. The key here is that string. replaceall () uses regular expression as the parameter. However, Java strings have similar processing for escape characters. First, Java will interpret "//" as a string (including two char) -- "//", which is what you see in the JDK document. Next, because replaceall uses a regular expression as the parameter, "//" is interpreted as a RegEx. For a RegEx, this represents a character, that is, "/". For the next eight/s, it will be interpreted as "//". In other words, assume that string. replaceall () is a common string instead of a RegEx parameter, so write the code as follows: String target = source. replaceall. |
----------------------------------------------------------------
[] Escape [[], [] in the database
String sfilenum = "test [name]" in Java;
Sfilenum = sfilenum. replaceall ("// [", "AA ");
Sfilenum = sfilenum. replaceall ("//]", "BB ");
Sfilenum = sfilenum. replaceall ("AA", "[]");
Sfilenum = sfilenum. replaceall ("BB", "[]");