To remove parentheses, dashes, and spaces from a phone number using a regular expression in Java, you can use the following pattern:
import java.util.regex.Matcher; import java.util.regex.Pattern; public class CleanPhoneNumber { public static void main(String[] args) { String phoneNumber = "(123) 456-7890"; // Remove parentheses, dashes, and spaces String cleanedNumber = phoneNumber.replaceAll("[\\s()-]", ""); System.out.println("Original Phone Number: " + phoneNumber); System.out.println("Cleaned Phone Number: " + cleanedNumber); } } In this example:
[\\s()-] is the regular expression.\\s matches any whitespace character (spaces).()- matches literal parentheses and dash characters.The replaceAll("[\\s()-]", "") method replaces all occurrences of spaces, parentheses, and dashes with an empty string, effectively removing them.
After running this program, the output will be:
Original Phone Number: (123) 456-7890 Cleaned Phone Number: 1234567890
Modify the phoneNumber variable as needed. Adjust the regex if you want to include or exclude specific characters based on your requirements.
"Java code to remove parentheses from a phone number"
String cleanedNumber = phoneNumber.replaceAll("[()]", ""); "Java code to eliminate dashes from a phone number"
String cleanedNumber = phoneNumber.replaceAll("-", ""); "Java regex to strip spaces from a phone number"
String cleanedNumber = phoneNumber.replaceAll("\\s", ""); "Java code to remove parentheses and dashes from a phone number"
String cleanedNumber = phoneNumber.replaceAll("[()-]", ""); "Java regex to replace parentheses, dashes, and spaces in a phone number"
String cleanedNumber = phoneNumber.replaceAll("[()\\s-]", ""); "Java code to strip non-numeric characters from a phone number"
String cleanedNumber = phoneNumber.replaceAll("\\D", ""); "Java regex for removing formatting from a phone number"
String cleanedNumber = phoneNumber.replaceAll("[()\\s-]", ""); "Java code to clean phone number by removing special characters"
String cleanedNumber = phoneNumber.replaceAll("[^0-9]", ""); "Java regex to remove all non-digit characters from a phone number"
String cleanedNumber = phoneNumber.replaceAll("\\D", ""); "Java code to sanitize phone number by removing unwanted characters"
String cleanedNumber = phoneNumber.replaceAll("[()\\s-]", ""); cucumber-jvm gitlab-ce in-clause show-hide file-handling sqlparameter linestyle pos-for-.net controllers inline-images