Tag Archives: regex

Dollar sign($) and the ReplaceAll Gotchas

/* Vietnamese summarization: String.replaceAll() là một hàm tiện dụng của Java, nhưng do cách đặt tên lại dễ bị hiểu nhầm tác dụng với String.replace(). Bài viết trình bày sự khác biệt giữa hai hàm này qua một trường hợp nhầm lẫn ngớ ngẩn của người viết. */

Today I got a “big” mistake, which take a fairly long time to solve. It’s a problem related to String.replaceAll() function of Java. The experience is so hot that I want to share it immediately.

Here’s the simplified problem: I need to construct a template for sending Email. The web application will take the template and insert user information into it. This task is performed by replacing some placeholder by user true information, for example:

Template: {USER_NAME}‘s hometown is {USER_COUNTRY}

Sending content: Long‘s hometown is Vietnam.

Usually, content = template.replaceAll(“{USER_NAME}”,username); is enough. It works well in most cases, but problem occurs when username contains some special characters, specifically, the dollar signs ($).

I know the “$” must have been interpreted different by Regex, so I try to escape the character. My first thought is that replacing “$” by “$”, but no matter how many “”, “QE” or “String.quote()” I put in, replaceAll still refuse to work.

I do a quick search on Google, and find this post. The writer once had the same problem but find no answer, so he decided to go for a quick fix. Temporarily, I accept the proposed solution.

But when asking the seniors about the solution, he tells me that there’s one thing I missed at the beginning: in Java6, ReplaceAll is for regex-replacement , in my case, I can use String.replace() instead!

In short, replaceAll() when you use Regex, if not, a String.replace() is enough.