S.mor S.mor - 7 months ago 36
Java Question

how to check if String contains only letters(a-z,A-Z), number and double slash("\\")

How can I write a method to check if string contains only number, letters, specific character(+_-/) and only double slash ("\\")

example:

"a2b/\" - false,

"d+sd\\ff" - true

i try use with

stringExample.matches("^[a-z-A-Z-0-9 +_-/]+");

but its not solve double slash ("\\")

Answer

For double backslash you need to escape it so use \\\\\\\\.

Pattern pattern = Pattern.compile("^([\\w +-/]|\\\\\\\\)+$");
System.out.println(pattern.matcher("a2b/\\").matches());
System.out.println(pattern.matcher("d+sd\\\\ff").matches());

Output:

false
true