This example will show how to parse a phone number from a formatted string using java, google guava, apache commons and google libphonenumber. A quick little background. The 3-3-4 phone number scheme was first developed by AT&T in 1947. The scheme represents area code, prefix and line number. This example attempts to shows a few flavors on how to parse, split or extract a phone number from a string.
Straight up Java
This snippet will parse a phone number separated with - using String.split. String.split will break the string into three arrays. The first array will represent the area code, second prefix and the third the line number.
Google Guava
This snippet will extract phone number from string using google guava. Using guava Splitter and a traditional formatting convention for phone numbers, we will split the String that contains the phone number on '-', ')' and '('. This will result in three elements within the Iterable representing area code, prefix and line number.
Apache Commons
Following a similar approach as the java example above, we will split a phone number from a string using apache commons StringUtils.split.
Google phone number library
This snippet will show how to parse a string that contains a phone number using google libphonenumber. PhoneNumberUtil is a utility class for international phone numbers and has a parse method built in where you pass in the string to parse and the default region.