#52 · Strings and dates

Find the bug · #52 · Strings and dates Medium Java

Cleaning a phone number deletes it

Removing the dots people type in phone numbers removes the whole number.

On this page

The report

Bug report

Some people type phone numbers with dots, like 98.76.54.32.10. The sign-up form strips the dots before saving, and every number typed that way is saved as empty.

The code

Read it first: what should it do? Then click the line where you think the bug is.

JavaClick the line you think is wrong
class Phones {
    // "98.76.54.32.10" -> "9876543210": drops the dots people type between digits.
    static String digitsOnly(String typed) {
        return typed.replaceAll(".", "");
    }
}

Read it, then pick a line.

What it prints

Running it on a small example prints the output on the left. It should print the output on the right.

The example
System.out.println("[" + Phones.digitsOnly("98.76.54.32.10") + "]");

It prints

[]

It should print

[9876543210]
Show the answer: the bug, the fix, and how you’d find it

The bug (line 4)

Line 4 uses replaceAll, whose first argument is a regular expression, and in a regex . means “any character”. So it replaces every character with nothing. replace treats its argument as plain text and still replaces every occurrence.

The fix

1class Phones {2    // "98.76.54.32.10" -> "9876543210": drops the dots people type between digits.3    static String digitsOnly(String typed) {4        return typed.replaceAll(".", "");4        return typed.replace(".", "");5    }6}

How you’d find it

  1. Reproduce: the cleaned number is an empty string.
  2. Everything vanished, not just the dots, so whatever is being matched matches everything. Check what replaceAll expects: a regex.
  3. In a regex, . is “any character”. You’d need "\\.", or plain replace.

The test that catches it

It fails on the code above and passes once it’s fixed. Keep it, so the bug can’t come back.

check(Phones.digitsOnly("98.76.54.32.10").equals("9876543210"), "dots removed");
check(Phones.digitsOnly("9876543210").equals("9876543210"), "no dots");

Where else this bites

  • split(".") in Java also takes a regex and returns an empty array.
  • JavaScript’s replace with a string only replaces the first match; use replaceAll there.
Your progress stays on this device.