正则表达式 Java 允许数字、字母、特殊字符(一些)

时间:2021-01-05 20:02:11

标签: java regex

我有一个文件名,假设上传 23_3.jpg。我想只允许使用字母、(.) 句点、(-) 连字符、下划线 (_)

Pattern p = Pattern.compile("[^a-z0-9_.]", Pattern.CASE_INSENSITIVE);
Matcher m = p.matcher(i.getFileName());

boolean specialCharFound = m.find(); //this will return true if any other characters are found

^ 表示不是 a-z、字母,我添加了 _ 和 .,但它不起作用。知道如何添加 '_' '.' '-' 字符?

3 个答案:

答案 0 :(得分:0)

你可以直接在字符类的末尾添加那些字符。

Pattern p = Pattern.compile("[^a-z0-9_. -]", Pattern.CASE_INSENSITIVE);

答案 1 :(得分:0)

不确定“^”在做什么。我想您想删除它。

您需要使用斜线对特殊字符进行转义。我认为只有'.'应该被转义并且 - 并且_不需要转义。

试试: [a-z0-9_-.]

也许 - 和 _ 对 CASE_INSENSITIVE 有问题,请考虑 Pattern.UNICODE_CASE。或者考虑不区分大小写并添加 A-Z。

试试: [A-Za-z0-9_-.],没有 CASE_INSENTIVE

答案 2 :(得分:0)

使用Pattern.compile("[\\w\\s.-]+") m.matches()

Pattern p = Pattern.compile("[\\w\\s.-]+");
Matcher m = p.matcher(i.getFileName());
boolean isValid = m.matches();

regex proof

说明

[\w\s.-]+                any character of: word characters (a-z, A-
                           Z, 0-9, _), whitespace (\n, \r, \t, \f,
                           and " "), '.', '-' (1 or more times
                           (matching the most amount possible))
相关问题