Home > Software design >  Regex pattern to check if string has no special characters - Java
Regex pattern to check if string has no special characters - Java

Time:06-07

I want to check if a string contains no special characters like @, $ etc and include only alphanumerics and special characters like "-", "."

I have used regex pattern as below, but none of them is working

  1. String regex = "^[a-zA-Z0-9_-.]*$";

  2. String regex = " /^[a-z0-9] (?:[._-][a-z0-9] )*$/i";

  3. String regex = "^([-.A-Za-z0-9]){1,20}$";

  4. String regex = "^[a-zA-Z0-9_-.]*";

if (r.getTest().matches(regex)){}

Edit:

The regex in the answers is working fine, but when added it as condition in the code, the code is always returning false, saying it contains special characters, when all I have in the string are alphanumerics, and dots(.).

None of them is working. Any help is much appreciated.

CodePudding user response:

I see one big issue with your first regex, and that's the -. Between [ and ], every - means a range except if it's escaped, or if it's the first or last character. With what you have now, I get an exception:

Exception java.util.regex.PatternSyntaxException: Illegal character range near index 13
^[a-zA-Z0-9_-.]*$

If I move the - to the end, I can successfully create a pattern that should work.

CodePudding user response:

You missed a \ before the -. You should use

^[a-zA-Z0-9_\-.]*$

See the demo

  • Related