简体   繁体   English

使用正则表达式限制特殊字符

[英]Limit special characters with Regex

I want my regex to match any string with "special" characters other than . 我希望我的正则表达式匹配带有以外的“特殊”字符的任何字符串. and / . / The other special characters are on a sort of blacklist. 其他特殊字符在某种黑名单上。 However, at runtime, I get an Illegal repetition error. 但是,在运行时,出现Illegal repetition错误。 How can I resolve that? 我该如何解决?

Pattern regex = Pattern.compile("!@#$%^&*()-_+=|\\}]{[\"':;?><,");
Matcher matcher = regex.matcher(key);
if (matcher.find()) {
    return false;
}

Probably it would be better to just specify what is allowed instead of what is denied: 最好只指定允许的内容而不是拒绝的内容:

Pattern regex = Pattern.compile ("^[\\w\\s\\./]*$");
if (!regex.matcher(key).matches ()) return false;

This allows only letters, digits, whitespace, dot ('.') and slash ('/'). 这仅允许使用字母,数字,空格,点('。')和斜杠('/')。

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

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