[英]validate empty variable regex
I have a regex scipt which validate a field variable for some extensions (pdf, doc, jpeg, jpg, and png). 我有一个正则表达式scipt,用于验证某些扩展名(pdf,doc,jpeg,jpg和png)的字段变量。 But sometimes, this field can be empty.
但有时,此字段可以为空。 I see on some topics that "^$" can solved my problem.
我在某些主题上看到“ ^ $”可以解决我的问题。 I try a lot of combinaisons (cause I do not know regex) but it doesn't work.
我尝试了很多组合(因为我不知道正则表达式),但是它不起作用。 I give you my current code:
我给你我当前的代码:
import java.util.regex.Matcher;
import java.util.regex.Pattern;
String REGEX = "([^#@]+(\\.(?i)(pdf|doc|docx|jpeg|mp3|jpg|png))\$)";
Pattern pattern = Pattern.compile(REGEX);
Matcher matcher = pattern.matcher(field_Fichier1.getFileName());
return matcher.matches();
Thanks for your help 谢谢你的帮助
// Mine = doesn't work for empty field
//String REGEX = "([^#@]+(\\.(?i)(pdf|doc|docx|jpeg|mp3|jpg|png))\$)";
// Anubhava = doesn't work for empty field
//String REGEX = "([^#@]+(\\.(?i)(pdf|doc|docx|jpeg|mp3|jpg|png)))?";
// or
//String REGEX = "([^#@]+(\\.(?i)(pdf|doc|docx|jpeg|mp3|jpg|png)))";
// Bohemian = can't be run = error: "Groovy:illegal string body character after dollar sign;"
String REGEX = "^$|([^#@]+(\\.(?i)(pdf|doc|docx|jpeg|mp3|jpg|png))\$)";
Why do you have \\$
in your regex. 为什么在正则表达式中有
\\$
。 You can just make your whole regex optional to allow for empty string match: 您可以将整个正则表达式设为可选,以允许空字符串匹配:
String REGEX = "([^#@]+(\\.(?i)(pdf|doc|docx|jpeg|mp3|jpg|png)))?";
?
in the end will make whole regex match optional thus allowing it match ""
as well. 最后将使整个正则表达式匹配成为可选,从而使它也与
""
匹配。
Just add ^$|
只需添加
^$|
to the front of your regex: 在您的正则表达式前面:
String REGEX = "^$|([^#@]+(\\.(?i)(pdf|doc|docx|jpeg|mp3|jpg|png))\$)";
Note that I haven't checked your existing regex - I'm assuming it works for non-blank input. 请注意,我尚未检查您现有的正则表达式-我假设它适用于非空白输入。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.