Method - String replaceAll(String regex, String replacement)

This method replaces each substring of the subject string that matches the given regular expression with the replacement String. As the name implies, replaceAll replaces all the matching occurrences of the input String. Note that we can also supply a simple String containing no regex meta character in the first argument.

Calling this method is equivalent to a call to the following:

Pattern.compile(regex).matcher(input).replaceAll(replacement); 
Note: We will cover Pattern and Matcher APIs in Chapter 5, Introduction to Java Regular Expression APIs - Pattern and Matcher Classes.

The replacement string allows the use of references to substrings, represented by the captured groups used in the regular expression. These references can be of two types:

  • Numbered references: These are written as $n, where n is a number, such as $1, $2, and $3, which represent a reference to each of the captured groups in the regular expression
  • Named references: These are written as ${groupName}, where groupName is the name of the captured group in the regular expression

To place a literal dollar or literal backslash in the replacement string, we need to escape these characters using double backslash (\).

Here, at this point, you should understand the difference between back-reference and replacement reference. Back-reference is used in the regular expression pattern itself and is written as 1,2,3, and so on for a numbered group's back-reference and k<groupName> for a named group's back-reference. However, replacement reference is either written as $1, $2, $3, for a numbered group's reference or ${groupName} for a named group's reference.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.119.131.10