Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to extract a phone number for a string using regular expression?

Tags:

java

string

regex

If I have a string that contains the following: This is 1 test 123-456-7890
I need to extract 1234567890 as a phone number. I don't want to extract the number 1 that is before test.
How can I do that using regular expressions in java?

I know a way but I am not sure if it is the best solution:

String inputString = "This is 1 test 123-456-7890";
string result =  inputString.replaceAll("(\\d{3})-(\\d{3})-(\\d{4})",""); 
String phoneNumber = inputString.replace(result, "");
like image 455
Wael Avatar asked Feb 27 '12 11:02

Wael


People also ask

How do you get a number from a string in regex?

To get the list of all numbers in a String, use the regular expression '[0-9]+' with re. findall() method. [0-9] represents a regular expression to match a single digit in the string. [0-9]+ represents continuous digit sequences of any length.

How do I extract a phone number from a string in Python?

Extract Phone Numbers From Text We can use the phonenumbers library to extract phone numbers from a text with Python. The handy phonenumbers. PhoneNumberMatcher() method iterates the text and extract any phone number, whether it is in a domestic or international format.

Can you use regex on numbers?

The regex [0-9] matches single-digit numbers 0 to 9. [1-9][0-9] matches double-digit numbers 10 to 99. That's the easy part. Matching the three-digit numbers is a little more complicated, since we need to exclude numbers 256 through 999.


2 Answers

The best and standard way is use libphonenumber. There is a findNumbers function you can use. Here is a code snippet

public static void  extractPhoneNumber(String input){


    Iterator<PhoneNumberMatch> existsPhone=PhoneNumberUtil.getInstance().findNumbers(input, "IN").iterator();

    while (existsPhone.hasNext()){
        System.out.println("Phone == " + existsPhone.next().number());
    }
}
like image 143
Abhijit Mazumder Avatar answered Nov 11 '22 21:11

Abhijit Mazumder


The following code will check for the phone number in the string you mention and print it:

String str = "This is 1 test 123-456-7890";

Pattern pattern = Pattern.compile("\\d{3}-\\d{3}-\\d{4}");
Matcher matcher = pattern.matcher(str);
if (matcher.find()) {
    System.out.println(matcher.group(0));
}

But, as pointed out in other answers, many phone numbers (especially not international ones) will not match the pattern.

like image 30
user829876 Avatar answered Nov 11 '22 19:11

user829876