How to use regular expressions (\b, \w) in Freemarker?

Viewed 9281
${str?replace("\d+", "", "r")};

I wanted to use \d to remove numbers, but it didn't work!!!

But ${str?replace("[0-9]", "", "r")}; works!!!

So, I wanna know how to use regex like \d, \b, \w, etc?

1 Answers

You need to double the backslashes:

${str?replace("\\d+", "", "r")};

This is because string escaping rules are applied before regex escaping rules. So the string "\\d" is translated to the regex \d which then matches a digit.

If your string is "\d", the string processor translates it to a literal d (because \d is not a recognized string escape sequence, so it's ignored).

Related