I am trying to compile following regex


String fileNameRegex = '/^\[~`!@#$%^&*()_+=\[\]\{}|;':",.\/<>?a-zA-Z0-9-\w\s\]+$/';
Pattern FileNamePattern = Pattern.compile(fileNameRegex);
String testString = '世界tes';
Matcher FileNameMatcher = FileNamePattern.matcher(testString);

enter image description here

I did escape special charters with '\' , please advise.


enter image description here


1 Answer 1


The simple answer, as already stated in the comments, is that you need to use double-backslashes to escape things in regex in Apex.

So insted of

String fileNameRegex = '/^\[~`!@#$%^&*()_+=\[\]\{}|;':",.\/<>?a-zA-Z0-9-\w\s\]+$/';

You'd need

String fileNameRegex = '^[~`!@#$%^&*()_+=\\[\\]\\{\\}\\|;\':",.\\\\/<>?a-zA-Z0-9-\\w\\s]+$';

Note that in addition to the doubling of backslashes, I also:

  • Escaped the single quote in (what I'm assuming is) your character class that you're trying to build, but only once (since it is a valid escape sequence outside of regex)
  • Escaped the pipe and closing curly brace
  • Unescaped the square braces near the start and end
  • Getting a literal backslash character requires 4 total backslashes in Apex
  • The leading and trailing / are removed (they aren't needed, and in fact make your regex non-functional)

That is sufficient to get this to run (though not necessarily produce the desired result).

It looks to me like you're attempting to detect printable ASCII characters. If that is the case, then you can make your life a whole lot simpler by using POSIX Character Classes.

i.e. String fileNameRegex = '^\\p{Print}+$';

  • @NachiketDeshpande I think you've missed the most important point here. You should use a POSIX character class instead of that mess. Much less typing, much less escaping, much easier to read and maintain.
    – Derek F
    Oct 7, 2022 at 19:06
  • Thanks @Derek for suggestion will keep in mind. Oct 7, 2022 at 19:07
  • +1 to your answer , (accepted) Oct 7, 2022 at 19:09
  • Wondering where my comment on the question disappeared to... ho hum.
    – Phil W
    Oct 7, 2022 at 21:08
  • @PhilW admin might have updated it , I didn't do anything :) , you can add that comment here again , I'll upvote :) Oct 7, 2022 at 21:20

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .