I have set up a regex to match couple of strings. When I use this regex in Apex class directly as string, it works correctly. However when i use the same regex from a custom Text field in Custom Settings it gives below error

System.StringException: Invalid regex: Illegal character range near index 8 [\d\s-#+@]{7,}

Tried to find a way, however all in vain.

Regex I am using is [\\d\\s-#+@]{7,}

Can anybody assist here in resolving this.

Regards Nitesh


When you're writing Apex Code, the compiler interprets \ as an escape meant for the source code. The Pattern class interprets \ as an escape character as well. Therefore, when you use [\\d\\s-#+@]{7,}, that means that you're actually passing in literal \ characters. It becomes interpreted as:

[ \ d \ s-# + @ ]{7,}
| 2 3 2  4  5 6 | 7

1: Match any character in this set
2: Match a literal "\"
3: Match a literal "d"
4: Match the range "s" through "#"
5: Match a literal "+"
6: Match a literal "@"
7: Match at least 7 times consecutively

The problem here is #4: "s" comes after "#", so the compiler won't allow it. It would allow "#" through "s", but this is not your intent.

When you're using data from a string (a label, custom setting, user input, etc), you do not escape the \, because you're not compiling Apex Code. The regex, as you've written it, would look like the following source code:

Pattern p = Pattern.compile('[\\\\d\\\\s-#+@]{7,}');

To fix this, remove the escape characters that you used to get them in the source code.

The custom setting's value should be:

  • Thanks sfdcfox! This worked. If you do not mind can i ask you one more question. I tried to we negate in Apex, but that too was not working for me. Is there any specific things that works differently for negate regex in Apex. Suppose I want to exempt strings starting with + , 0, # and contains @. – Nitesh Jan 21 '18 at 12:41
  • @Nitesh Assuming truth allows the code to continue, you could use OR (|): ^([+0#].*@.*)|([\d\s-#+@]{7,})$ (note: did not test this, so you might want to play with it a bit). You might want to read the Pattern class from Java for more explanation. – sfdcfox Jan 21 '18 at 18:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.