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, "");
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.
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.
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.
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());
}
}
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.
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