Search code examples
javaregexspringjava-8special-characters

Regex pattern to check if string has no special characters - Java


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.


Solution

  • You missed a \ before the -. You should use

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

    See the demo