![]() |
VOOZH | about |
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.
Original String: Hello123 World456 String after replacing digits: Hello*** World***
String replaceAll(String regex, String replacement)
Parameters:
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.
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 '@' .
Original String: The numbers are 25, 100, and 200. String after replacing large numbers: The numbers are 25, @, and @.