简体   繁体   English

Java正则表达式验证

[英]Java Regular expression validation

I want to validate a string which allows only alpha numeric values and only one dot character and only underscore character in java . 我想验证一个字符串,该字符串在Java中仅允许字母数字值和仅一个点字符且仅包含下划线字符。

String fileName = (String) request.getParameter("read");

I need to validate the fileName retrieving from the request and should satisfy the above criteria 我需要验证从请求中检索的fileName,并且应该满足上述条件

I tried in "^[a-zA-Z0-9_'.']*$" , but this allows more than one dot character 我在"^[a-zA-Z0-9_'.']*$"尝试过,但这允许多个点字符

I need to validate my string in the given scenarios , 我需要在给定的情况下验证我的字符串,

1 . 1。 Filename contains only alpha numeric values . 文件名仅包含字母数字值。 2 . 2。 It allows only one dot character (.) , example : fileRead.pdf , fileWrite.txt etc 3 . 它仅允许使用一个点字符(。),例如:fileRead.pdf,fileWrite.txt等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 : 您应该使用String.matches()方法:

System.out.println("My_File_Name.txt".matches("\\w+\\.\\w+"));

You can also use java.util.regex package. 您也可以使用java.util.regex包。

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 有关REGEX和JAVA的更多信息,请参见以下页面: https : //docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html

You could use two negative lookaheads here: 您可以在此处使用两个否定的前行:

^((?!.*\..*\.)(?!.*_.*_)[A-Za-z0-9_.])*$

Each lookahead asserts that either a dot or an underscore does not occur two times, implying that it can occur at most once. 每个先行断言,无论是点或下划线不会出现两次,这意味着它可以最多出现一次。

It wasn't completely clear whether you require one dot and/or underscore. 不清楚是否需要一个点和/或下划线。 I assumed not, but my regex could be easily modified to this requirement. 我以为不是,但是我的正则表达式可以很容易地修改为此要求。

Demo 演示版

You can first check the special characters which have the number limits. 您可以首先检查具有数字限制的特殊字符。 Here is the code: 这是代码:

int occurance = StringUtils.countOccurrencesOf("123123..32131.3", ".");

or 要么

int count = StringUtils.countMatches("123123..32131.3", ".");

If it does not match your request you can discard it before regex check. 如果它不符合您的要求,则可以在进行正则表达式检查之前将其丢弃。 If there is no problem you can now put your String to alphanumeric value check. 如果没有问题,您现在可以将String放在字母数字值检查中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM