1

I wrote one regular expression for catching any special characters in the text.

regular expression: (?i)[$&+,:;=?@#|'<>.-^*()%!]

I am passing a text "Testing" but getting output that the text contains special characters. But as soon as i pass, "testing" with small "t", i am getting no error.. Can you please help ?

code:

String REGEX = "(?i)[$&+,:;=?@#|'<>.-^*()%!]";
String fieldValue="Testing";
java.util.regex.Pattern pattern = java.util.regex.Pattern.compile(REGEX);
java.util.regex.Matcher matcher = pattern.matcher(fieldValue);
if (matcher.find()) {
    String strWarningMessage = "Field value cannot contain Special Characters";
    System.out.println(strWarningMessage);
}
else
    System.out.println("OK");
4
  • 1
    Post your code please. Commented Oct 29, 2014 at 6:54
  • 1
    I've edited the parenthesis in your if, I hope it was a typo only when you posted the question. Isn't it? Commented Oct 29, 2014 at 6:57
  • I don't think you should be getting an error. What's the message? Commented Oct 29, 2014 at 7:15
  • It's not an error message, it prints my warning message only: Field value cannot contain Special Characters Commented Oct 29, 2014 at 7:15

2 Answers 2

1

Move your - to the end of the character class or escape it:

"[$&+,:;=?@#|'<>.^*()%!-]"

And the (?i) can be dropped, since your pattern doesn't specify any character which has different cases.

In your original regex, .-^ is specifying a range of character from . (U+002E) to ^ (U+005E), which contains uppercase A-Z and digits 0-9.

Sign up to request clarification or add additional context in comments.

2 Comments

Shouldn't have ^? OP doesn't want to match any special character.
@MarounMaroun: Don't know. There are numerous other "special character" in Unicode.
1

Your problem is character -. When symbol group [...] contains this character, there are two possible interpretation:

  • symbol - (when it placed in first position after [)
  • symbol range (when it placed in any position after [ except first)

So you need move - to start of symbol group.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.