VOOZH about

URL: https://www.geeksforgeeks.org/java/replace-all-digits-in-a-string-with-a-specific-character-in-java/

⇱ Replace all Digits in a String with a Specific Character in Java - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

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

Last Updated : 23 Jul, 2025

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.


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.


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 '@' .


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