I want to remove all special characters from a phone number string entry except + symbol. That too, if it is occurring only at first place. Example : +911234567890 should be valid but +91+1234#1234 should be invalid.
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  + ");
    }
 }
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With