At first glance, it's literally as if replace replaces only the first occurrence of the character (affected by JavaScript), ReplaceAll replaces all characters, but it's not the same as the replacement.
Public String replace (char Oldchar,char Newchar)
Returns a new string that is generated by replacing all the oldchar that appear in this string with Newchar. If Oldchar does not appear in the sequence of characters represented by this string object, a reference to this string object is returned. Otherwise, a new string object is created to represent a sequence of characters equal to the sequence of characters represented by this String object, except that each occurrence of the Oldchar is replaced by a newchar.
The public string ReplaceAll (string regex,string replacement) replaces this string with each substring of the given regular expression using the given replacement string. The Str.replaceall (Regex, repl) Form called by this method produces exactly the same result as the following expression:
Pattern.compile (regex). Matcher (str). ReplaceAll (REPL)
Parameters:
regex– the regular expression used to match this string
Returns: The resulting String
Thrown: patternsyntaxexception– If the syntax of the regular expression is invalid.
Practical application:
public static void Main (string[] arg) throws Ognlexception {
String s = "SDF\\A\\AA";
Replace the backslash in S with \ \
System.out.println (s);
System.out.println (S.replaceall ("\\\\", "\\\\\\\\"));
System.out.println (S.replace ("\", "\\\\"));
}
You can see that both of the above return the same substitution result.
The key here is that String.replaceall () is used as a parameter by regular expression. But the string of Java itself has similar processing for escape characters. First, Java interprets "\\\\" as a string (containing two char)--"\ \" which is what you see in the JDK's documentation.
Next, because ReplaceAll is a regular expression as an argument, "\ \" is interpreted as a regex. For a regex this represents a character, that is, "\". For the next 8, it will eventually be interpreted as "\ n".
In other words, suppose String.replaceall () is a normal string rather than a regex, so write code: String target = Source.replaceall (' \ n ', ' \\\\ '); It's OK.
No related posts.