Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Regular expression validation

Tags:

java

string

regex

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 ?

like image 875
user3518223 Avatar asked Dec 02 '22 11:12

user3518223


1 Answers

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

like image 190
Valentin Genevrais Avatar answered Jan 01 '23 19:01

Valentin Genevrais