I want to validate a string which allows only alpha numeric values and only one dot character and only underscore character in java .
String fileName = (String) request.getParameter("read");
I need to validate the fileName retrieving from the request and should satisfy the above criteria
I tried in "^[a-zA-Z0-9_'.']*$"
, but this allows more than one dot character
I need to validate my string in the given scenarios ,
1 . Filename contains only alpha numeric values . 2 . It allows only one dot character (.) , example : fileRead.pdf , fileWrite.txt etc 3 . it allows only underscore characters . All the other symbols should be declined
Can any one help me on this ?
You should use String.matches() method :
System.out.println("My_File_Name.txt".matches("\\w+\\.\\w+"));
You can also use java.util.regex package.
java.util.regex.Pattern pattern =
java.util.regex.Pattern.compile("\\w+\\.\\w+");
java.util.regex.Matcher matcher = pattern.matcher("My_File_Name.txt");
System.out.println(matcher.matches());
For more information about REGEX and JAVA, look at this page : https://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With