Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove all special characters from a phone number string entry except + occurring only at first place [closed]

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.

like image 735
S P Avatar asked Jun 24 '13 06:06

S P


2 Answers

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!

like image 194
Nargis Avatar answered Oct 22 '22 09:10

Nargis


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  + ");
    }
 }
}
like image 31
Yakiv Mospan Avatar answered Oct 22 '22 07:10

Yakiv Mospan