preface

Let’s start with a quick overview:

  1. Replace () and replaceAll() are common ways to replace strings;
  2. Both are full replacements. You can replace a character or string in the source string with a specified character or string.
  3. If you want to replace only the first occurrence, use replaceFirst();
  4. This method is also based on regular expression substitution, but unlike replaceAll(), only replaces the first occurrence of the string;
  5. The substitution arguments used by replaceAll() and replaceFirst() can be regular strings or regular expressions;
  6. If the arguments used by replaceAll() and replaceFirst() are not based on regular expressions, they are just as effective and efficient as replacing () with a string.

Note: After a replacement operation, a new object is returned, and the contents of the source string are unchanged.

Source code analysis

To take a look at the source code for the definition of the two methods, I have extracted a paragraph from each:

* String.class */ ... /** * Replaces each substring of this string that matches the literal target sequence * with the specified literal replacement sequence ... Replaces each substring of the string that matches the literal target sequence with the specified literal replacement sequence. */ public String replace(CharSequence target, CharSequence replacement) { return Pattern.compile(target.toString(),Pattern.LITERAL). matcher(this).replaceAll(Matcher.quoteReplacement(replacement.toString())); }... /** * Replaces each substring of this string that matches the given regular expression * with the given replacement... Replaces each substring of the string that matches the given regular expression with the given substitution. */ public String replaceAll(String regex, String replacement) { return Pattern.compile(regex). matcher(this).replaceAll(replacement); }...Copy the code

Through the method definition, we see that replaceAll() was given the ability to match regular expressions when it was defined. Through the source code, two points can be summarized:

  1. String.replace() and string.replaceAll () call the same method, both matcher.replaceAll ();
  2. The replaceAll() method does not pass “pattern.literal”;

It is this slight difference that determines that the replaceAll() method takes precedence over the argument regex being replaced as a regular expression.

  • If it is a regular, the regular replacement is performed.
  • If it’s a string, perform string substitution, and replace() is the same.

ReplaceAll () source code analysis

Example: The “pattern.literal” parameter affects business logic:

1. String.replaceAll(String regex, String replacement)

It calls three functions:

  • Pattern.compile(String Regex) — Compile (parse) regular expressions to obtain Pattern objects;
  • Pattern.matcher(CharSequence input) — Get matcher;
  • Matcher.replaceall (String replacement) – Replace the String;

As the name suggests, the main point we need to explain is in the pattern.pile (String regex) method.

Pattern.compile(String regex) function follows:

It returns a Pattern object.

3. The constructors of Pattern are as follows:

This constructor is private and cannot be called directly by other classes. It can only be called with compile(String regex, int flags) and compile(String regex, int flags) of the Pattern class. This constructor calls compile(), and processing of the regex argument takes place inside this function!!

4. Pattern.compile() function follows:

Among them:

  • The “LITERAL” parameter in “LITERAL” is the one we mentioned above.
  • If — else statement (①);
  • MatchRoot = expr(lastAccept); A method that obtains a regular expression to match the root. If executed, the regular expression is matched.

Well, the next code I will not demonstrate, interested partners can have a look.

Code demonstrates

With all the theoretical stuff said, write a few lines of code to verify it:

@Test public void replaceTest() { String str1 = "Aoc.Iop.Aoc.Iop.Aoc"; String str2 = "Aoc. Iop.aoc. Iop.aoc "; String str3 = "Aoc.Iop.Aoc.Iop.Aoc"; String str11 = str1.replace(".", "#"); // str11 = "Aoc#Iop#Aoc#Iop#Aoc" String str22 = str2.replaceAll(".", "#"); // str22 = "###################" String str33 = str3.replaceFirst(".", "#"); // str33 = "#oc.Iop.Aoc.Iop.Aoc" }Copy the code

As a result of “.” A symbol that is part of a regular expression, so the replaceAll() method performs a regular replacement.

Escape symbol – “\”, need to be careful:

  • “\” is an escape character in Java, so you need two to represent one. For example System. Out. Println (” \ \ “); Just print out a “\”;
  • “\” is also an escape character in regular expressions (the arguments to replaceAll() are regular expressions) and requires two to represent one. So: “\\\\” is converted to “\\” by Java, which in turn is converted to “\\” by regular expressions.

Look at an example:

@Test public void replaceTest() { String str1 = "blog.csdn.net/weixin_44259720/"; String str2 = "blog.csdn.net/weixin_44259720/"; String str11 = str1.replace("/", "\\"); / / escaped String str22 = str2. ReplaceAll ("/", "\ \ \ \"); Str11 = "blog.csdn.net\weixin_44259720\" str22 = "blog.csdn.net\weixin_44259720\"Copy the code

summary

  1. Replace takes char and CharSequence arguments, which can be used to replace characters as well as strings (CharSequence).
  2. ReplaceAll takes a regex, or regular expression based replacement. For example, you can use replaceAll (“\d”, “*”) to replaceAll numeric characters in a string with asterisks;
  3. The String class performs the substitution operation and returns a new object, with the contents of the source String unchanged.