为什么输入必须接受的字符时会产生错误?

发布于 2024-12-23 05:16:28 字数 581 浏览 1 评论 0原文

我正在 Java 中使用正则表达式来检查密码字段的输入。以下是检查密码的代码:

final Pattern check = Pattern.compile( "^[a-z0-9A-Z!$%*()-_[]{};:@#<>,./?\\|]+$");

if (!check.matcher(password).matches()) {
    errors.put("password", "Invalid input");
}

当我提交包含符号的输入,例如 % 时,会生成以下异常:

异常

java.util.regex.PatternSyntaxException:附近未封闭的字符类 索引 37 ^[a-z0-9A-Z!$%*()-_[]{};:@#>>,./?\|]+$ ^

我已经在同一代码中使用了其他正则表达式,并且它们工作正常......只有这部分给我带来了麻烦。

你们中有人知道这个错误的原因吗?

提前感谢您的帮助!

I am using regular expressions in Java to check the input of a password field. The following is the code for checking the password:

final Pattern check = Pattern.compile( "^[a-z0-9A-Z!$%*()-_[]{};:@#<>,./?\\|]+$");

if (!check.matcher(password).matches()) {
    errors.put("password", "Invalid input");
}

When i submit an input containing symbols, for example %, the following exception is being generated:

exception

java.util.regex.PatternSyntaxException: Unclosed character class near
index 37 ^[a-z0-9A-Z!$%*()-_[]{};:@#<>,./?\|]+$
^

I've already used other regex expressions in this same code and they work fine... Only this part is giving me trouble.

Does any of you maybe know the cause for this error?

Thanks for your help in advance!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

番薯 2024-12-30 05:16:28

您的字符类有两个问题:

  • 您没有转义其中的 ]
  • - 位置使其不明确。

更重要的是,Java 还要求您转义 [ (其他正则表达式引擎不会要求这样做):

您应该这样编写:

final Pattern check = Pattern.compile("^[-a-z0-9A-Z!$%*()_\\[\\]{};:@#<>,./?\\\\|]+$");

Your character class has two problems:

  • you don't escape the ] in it,
  • the - placement makes it ambiguous.

What's more, Java also requires that you escape the [ (other regex engines won't require that):

You should write it a such:

final Pattern check = Pattern.compile("^[-a-z0-9A-Z!$%*()_\\[\\]{};:@#<>,./?\\\\|]+$");
世俗缘 2024-12-30 05:16:28

我认为你应该逃避其中一些角色?至少是括号,因为您正在使用它们来开始您的角色类。

I think you should escape some of those characters? At least the brackets, as you are using them to start your character class.

情话墙 2024-12-30 05:16:28

也许是由于复制,但正则表达式遗漏了一些反斜杠:

^[a-z0-9A-Z\\!\\$%\\*\\(\\)\\-_\\[\\]\\{\\};:@#<>,\\./\\?\\|]+$

http://docs.oracle.com/javase/6/docs/api/java/util/regex/Pattern.html

Maybe it is due to the copying, but the regex misses some backslashes:

^[a-z0-9A-Z\\!\\$%\\*\\(\\)\\-_\\[\\]\\{\\};:@#<>,\\./\\?\\|]+$

http://docs.oracle.com/javase/6/docs/api/java/util/regex/Pattern.html

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文