Converting backslashes to slashes
A medium Java puzzle in the string handling family. One line below contains a real bug. Try to spot it first, then read why it fails and how to fix it.
Highlighted: line 3. Play this one as a puzzle without the answer.
What is wrong
replaceAll treats its first argument as a regular expression. The Java string "\" is a single backslash, which is an incomplete escape in a regex, so the call throws PatternSyntaxException.
The fix
How to avoid it next time
Use replace for literal text and replaceAll only when you need a pattern.
Want the background? Read Regular expressions in the Java concepts library.
About string handling
Strings are immutable, split and replaceAll take regular expressions, and character encodings default to whatever the platform says. Small misunderstandings produce wrong output rather than errors.
In code review: Look at whether the return value of a String method is used, whether a pattern argument is a regex, and whether an encoding is named explicitly.
More puzzles in this family
Frequently asked questions
What is the bug in "Converting backslashes to slashes"?
replaceAll treats its first argument as a regular expression. The Java string "\" is a single backslash, which is an incomplete escape in a regex, so the call throws PatternSyntaxException. The faulty line is line 3: return windowsPath.replaceAll("\\", "/");
How do I fix it?
Replace it with: return windowsPath.replace("\\", "/");. Use replace for literal text and replaceAll only when you need a pattern.
How do I catch string handling in code review?
Look at whether the return value of a String method is used, whether a pattern argument is a regex, and whether an encoding is named explicitly.
Is there a new puzzle every day?
Yes. The daily Spot the Bug puzzle picks one of these snippets for each UTC day, with the difficulty set by the weekday. Your streak is stored only in your browser.