0

I have a problem with Freemarker. I want to remove all the special characters from text string in freemarker: "!"#$%&'()*+,-./:;<=>?@[]^_`{|}~". I tried writing regular expression for this but it is not working and facing some errors:

<#assign s = 'Foo bAr$%,*^%@()":& baar'>

${s?replace('["!"#$%&'()*+,-./\:;<=>?@[]^_`{|}~"]', '', 'r')}

Please help

Siddharth
  • 67
  • 7
  • Does this answer your question? [What special characters must be escaped in regular expressions?](https://stackoverflow.com/questions/399078/what-special-characters-must-be-escaped-in-regular-expressions) – Jasper de Vries Nov 21 '22 at 15:29
  • Hi, I tried the pattern: [^"!"#\$%&'\(\)\*\+,-\.\/\\:;<=>\?@\[\]\^_`\{|\}~"\s] on on https://regex101.com/, it works there but it is not working with freemarker, thats why I posted this question. Any suggestions please. – Siddharth Nov 21 '22 at 15:56
  • See https://stackoverflow.com/questions/33492200/freemarker-escape-regex-characters – Jasper de Vries Nov 21 '22 at 16:20
  • thanks, I am able to fix this issue now. – Siddharth Nov 21 '22 at 18:36

2 Answers2

1

You could simplify this solution like this unless there are other special characters you explicitely want to keep:

${s?replace("[^\\w]|_", "", "r")}
bdasliva83
  • 36
  • 4
0

I was able to remove these special characters after going through:

Freemarker escape regex characters I have used below expression to make it work. replace('[$%,*@():&"^!{}|~<>=""+-./;?_'`#\[\]\\ ]', '', 'r')

Siddharth
  • 67
  • 7