Rebooting
Rebooting

Reputation: 2938

Regex Value for Java Case Insensitive

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");

Upvotes: 1

Views: 167

Answers (2)

Sergii Lagutin
Sergii Lagutin

Reputation: 10671

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.

Upvotes: 1

nhahtdh
nhahtdh

Reputation: 56809

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.

Upvotes: 1

Related Questions