Open In App

Replace all Digits in a String with a Specific Character in Java

Last Updated : 23 Jul, 2025
Suggest changes
Share
Like Article
Like
Report

To replace all digits in a string with a specific character in Java, we can use the regular expressions and the replaceAll() method of the String class. This method allows to search for patterns in the string and replace them with a given character or substring.

Example 1: The below Java program demonstrates replacing all digits in a string with an asterisk (*) using the replaceAll() method.

Java
// Java program to replace all digits with an asterisk public class Geeks {    public static void main(String[] args)   {  // Declare and initialize the string  String s = "Hello123 World456";  // Replace all digits with an asterisk (*)  String s1 = s.replaceAll("[0-9]", "*");  System.out.println("Original String: " + s);  System.out.println("String after replacing digits: " + s1);  } } 

Output
Original String: Hello123 World456 String after replacing digits: Hello*** World*** 

Syntax

String replaceAll(String regex, String replacement)

Parameters:

  • regex: The regular expression to search for in the string. In our case, this will be a pattern to match digits, such as "[0-9]".
  • replacement: The string to replace the matched digits. This could be any character or substring. In this example, we used "*".

Return Type: The method returns a new string with the digits replaced by the specified character or substring.

Example 2: The below Java program demonstrates replacing all occurrences of the digit '5' in a string with the '@' character using the replaceAll() method.

Java
// Java program to replace only specific digit 5 with '@' public class Geeks {    public static void main(String[] args)   {  // Declare and initialize the string  String s = "My phone number is 555-1234";  // Replace only digit '5' with '@'  String s1 = s.replaceAll("5", "@");  System.out.println("Original String: " + s);  System.out.println("String after replacing digit 5: " + s1);  } } 

Output
Original String: My phone number is 555-1234 String after replacing digit 5: My phone number is @@@-1234 

Example 3: The below Java program demonstrates replacing all numbers greater than 100 in a string with the '@' .

Java
// Java program to replace numbers greater than 100 with '@' public class Geeks {    public static void main(String[] args) {    // Declare and initialize the string  String s = "The numbers are 25, 100, and 200.";  // Replace all numbers greater than 100 with '@'  String s1 = s.replaceAll("\\b[1-9][0-9]{2,}\\b", "@");  System.out.println("Original String: " + s);  System.out.println("String after replacing large numbers: " + s1);  } } 

Output
Original String: The numbers are 25, 100, and 200. String after replacing large numbers: The numbers are 25, @, and @. 

Article Tags :

Explore