-1

I've tried different ways to make the special character '-' work, but it doesn't seem to work when I try to test the regex within the code. The examples I tried were these

[^(a-zA-Z0-9\\\\@#$%!.'{}_-~`())]

The above one would not work as it searches for characters between '_' to '~'. Then I tried with

[^(a-zA-Z0-9\\\\@#$%!.'{}_~`()\\-)]
[^(a-zA-Z0-9-\\\\@#$%!.'{}_~`())]
[^(a-zA-Z0-9\\-\\\\@#$%!.'{}_~`())]

None of the above seem to be working if I give '-' in the string to search. The above expressions work when I try to test in regex tester online.

EXTERNAL_USER_INVALID_PATTERN = "[^(a-zA-Z0-9\\\\@#$%!.'{}_~`()\\-)]"
Pattern p = Pattern.compile(X.EXTERNAL_USER_INVALID_PATTERN);
if(p.matcher(objectName).find() || objectName.length()> X.EXTERNAL_USER_MAXLENGTH){
    throw new BusinessException("The group name does not conform to specification");
}

It always throws the given exception. All the other combinations without '-' seems to be working.

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
Varun Jain
  • 63
  • 2
  • 10
  • The `[^(a-zA-Z0-9\\-\\\\@#$%!.'{}_~\`())]` has the right way of escaping regex special chars in a Java string literal. However, it is a negated character class. Did you mean something like `String pat = "[a-zA-Z0-9\\-\\\\@#$%!.'{}_~\`())]"`? What is your pattern supposed to match? – Wiktor Stribiżew Jun 29 '17 at 06:43
  • Yes it is supposed to be negated. If the matcher returns TRUE, then it throws the given exception – Varun Jain Jun 29 '17 at 06:56
  • You understand you only check if a string contains at least one char that is not the one defined in your sets/ranges? Maybe you need `.matches()` (not `find()`) with `"[^...]+"` regex? – Wiktor Stribiżew Jun 29 '17 at 07:12
  • Does the answer below solve your issue? – Wiktor Stribiżew Jun 29 '17 at 07:32

1 Answers1

2

Hyphen characters have special meaning inside character classes. To include it, put it as first or as last character in the class. E.g. [-A-Z] or [^A-Z-].

Henry
  • 42,982
  • 7
  • 68
  • 84