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
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.
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.
Is the first argument of replaceAll plain text, or something else?
What it prints
Running it on a small example prints the output on the left. It should print the output on the right.
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
- Reproduce: the cleaned number is an empty string.
- Everything vanished, not just the dots, so whatever is being matched matches everything. Check what
replaceAllexpects: a regex. - In a regex,
.is “any character”. You’d need"\\.", or plainreplace.
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
replacewith a string only replaces the first match; usereplaceAllthere.