字母数字字符串的@Pattern - Bean 验证 [英] @Pattern for alphanumeric string - Bean validation

查看:31
本文介绍了字母数字字符串的@Pattern - Bean 验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在一个 bean 中有一个变量名.我想添加 @Pattern 验证以仅接受字母数字.

I have a variable name in a bean. I want to add @Pattern validation to accept only alphanumeric.

目前,我有这个.

 @NotNull
 @Pattern(regexp = "{A-Za-z0-9}*")
 String name;

但错误是正则表达式无效.我试过[A-Za-z0-9].但这也行不通.虽然没有错误.它将任何有效输入显示为失败.

But the error is Invalid regular expression. I tried [A-Za-z0-9]. But this is not working either. No errors though. It shows any valid input as failed.

推荐答案

你试试这个模式:^[A-Za-z0-9]*$

^[A-Za-z0-9]+$ 以避免空结果.

or ^[A-Za-z0-9]+$ to avoid empty results.

如果你想检查一个字符串是否只包含特定的字符,你必须添加锚点(^ 用于字符串的开头,$ 用于字符串的结尾)确保您的模式与整个字符串匹配.

If you want to check that a string contains only specific characters, you must add anchors (^ for beginning of the string, $ for end of the string) to be sure that your pattern matches the whole string.

大括号仅用于表示重复,例如:如果我想要两个 a:
a{2}
你不能把里面的字母.您可以在大括号之间找到字母的唯一情况是使用 UNICODE 字符类时:\p{L}(L 表示字母),\p{希腊语}\p{阿拉伯语}、...

Curly brackets are only used to express a repetition, example: if I want two a:
a{2}
You can't put letters inside. The only situation where you can find letters enclosed between curly brackets is when you use UNICODE character classes: \p{L} (L for Letters), \p{Greek}, \p{Arabian}, ...

这篇关于字母数字字符串的@Pattern - Bean 验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆