Remove all special characters from a phone number string entry except + occurring only at first place
You can use something like:
String number = "+91+1234#1234"
number=number.replaceAll("[\\D]", "")
This will replace all non digit characters with space but then for your additional "+" in the beginning ,you may need to add it as a prefix to the result.
Hope this helps!
The best way is to use regular expression:
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Main
{
public static void main(String[] args)
{
String sPhoneNumber = "+911234567890";
Pattern pattern = Pattern.compile("^[+]\\d*");
Matcher matcher = pattern.matcher(sPhoneNumber);
if (matcher.matches()) {
System.out.println("Phone Number Valid");
} else {
System.out.println("Phone Number must start from + ");
}
}
}
Scanner scan=new Scanner(System.in);
String input=scan.next();
String onlyDigits = input.replaceAll("[^0-9]+","");
System.out.println(onlyDigits);