Java .replaceAll()
The .replaceAll() method replaces every match of a specified regular expression with a given string.
Syntax
string.replaceAll(regex, repl);
regex: A string that defines the regular expression pattern.repl: The string that will replace every occurrence of the pattern found in the original string.
Note: If the objective is to search and replace a sequence of plain text without using a regex pattern, use the
.replace()method.
Example
The example below sanitizes a user inputted phone number by removing any non-digit characters:
public class Main {public static void main(String[] args) {String phoneNumber = "(123) 456-7890";String sanitizedPhoneNumber = sanitizePhoneNumber(phoneNumber);System.out.println(sanitizedPhoneNumber);}public static String sanitizePhoneNumber(String number) {return number.replaceAll("[^0-9]", "");}}
Note: When using regex metacharacters (e.g.
.,*,+,?,^,$,\\) in thereplstring, useMatcher.quoteReplacement(String)to ensure they are interpreted literally.
In this example, sanitizePhoneNumber is a method that takes a phone number and removes any non-digit characters. In the replaceAll() method, the [^0-9] pattern is passed for the regex argument and "" for the repl argument. This means that every non-digit character will be replaced with an empty string. Then the sanitized phone number is printed to the console:
1234567890
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn Java on Codecademy
- Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
- Includes 6 Courses
- With Professional Certification
- Beginner Friendly.75 hours
- Learn to code in Java — a robust programming language used to create software, web and mobile apps, and more.
- Beginner Friendly.17 hours