Strip Phone: Part 1

Some basic regular expression tasks are exposed through the standard String class. Therefore, there is no need to import the regular expression packages for many of the more basic tasks such as replacing or extracting text.

In this puzzle, we will try to extract a phone number from a user input. Like most problems, there are many possible ways to approach this. There are even multiple ways to approach this with regular expressions. Consider the problem of non-normalized input of user telephone numbers (to just list a few):

  • 650-555-5555
  • 612.555.5555
  • +1612.555.5555
  • (612) 555 5555

Instead of being clever and matching all possible inputs for a phone number (possible, and we'll work towards that), let's begin by doing the reverse, and instead of identifying the numbers, let's just remove anything that's not a number.

One predefined character class that matches all digits is identified id: \d
The reverse this character class, one that matches all non-digits is identified with a capital 'D': \D *note the backslash escape character to signal the beginning of a character class

For this puzzle, we will use the String.replaceAll(String regex, String replacement) method. Instead of matching a pattern, we'll just remove all non-digit numbers. For the regex parameter in the String.replaceAll(String regex, String replacement) method, pass in a regular expression that will match all non-digit characters. If you were going to remove a character from a String, what would you replace the character with? That is what you should add as the 'replacement' parameter.

*HINT: Rember to escape backslashes when using them in Java code. Regular expressions in Java aren't first-class language features. The syntax of a regular expression is expressed within a Java String. Since Java treats backslash characters, '\', as special escape characters, if you are using a backslash character, you must, in essence, double escape it. For instance, \d -> \\d

For further details, a good explanation of the details of how regular expressions are implemented in Java is found in the JavaDocs:

And a nice article on the linguistics of regular expressions:


Answers are hidden from search engines.
regular-expression coding language=java