简体   繁体   English

Java Regular Expression用于验证最后两个字符

[英]Java Regular Expression to validate last two characters

I want to validate an expression. 我想验证一个表达式。 I could able to achieve 90% however I am failing on one condition. 我能够达到90%但是我在一个条件下失败了。 How we can add an expression to make sure that particular character after few number of character should be an alphabet and next if any should be a number. 我们如何添加一个表达式来确保在少数字符后面的特定字符应该是一个字母,如果有的话应该是一个数字。

Eg: [A-Z1-9]{1,30}?[A-Z]{0,1}$[1-9]{0,1}

The pattern can have max 32 characters and last 2 characters are optional If the character exceeds 30 it should starts with an alphabet [AZ] and it should occur only once {0,1} And the 32nd character should be a number [1-9] and it should occur only once and should present if 31st char exists Could you help me please ? 模式最多可包含32个字符,最后2个字符是可选的如果字符超过30,则应以字母[AZ]开头,并且只应出现{0,1}一次,第32个字符应为数字[1-9] ,它应该你能帮我请只出现一次,应该存在,如果31日焦炭存在?

Try the following pattern. 尝试以下模式。 This matches 1-29 "normal" characters, or exactly 30 characters with your optional suffix. 这匹配1-29个“普通”字符,或者与可选后缀完全匹配30个字符。

//                  Matches 29 chars    Matches 30 chars plus suffix
//                        |                      |
//                ----------------------------------------------
//                |               ||                           |
String pattern = "([A-Z\\d]{1,29})|([A-Z\\d]{30}([A-Z]\\d){0,1})";
//                 ^^^^^^^^         ^^^^^^^^

The underlined parts ( ^^^^ ) should be adjusted to describe the set of characters you allow in the first 30 characters. 应调整带下划线的部分( ^^^^ )以描述前30个字符中允许的字符集。

Note: I've used 0-9 as valid numbers, which is more normal. 注意:我使用0-9作为有效数字,这更为正常。 If you really need 1-9 you can adjust the code. 如果你真的需要1-9你可以调整代码。

Your text is unclear. 你的文字不清楚。 If 31st character exists is the 32nd character optional or required? 如果存在第31个字符,则第32个字符是可选的还是必需的?

[A-Z1-9]{0,30}?(?:[AZ]|[AZ][1-9])?

This one allows 30 characters, 31 characters or 32 characters. 这个允许30个字符,31个字符或32个字符。

[A-Z1-9]{0,30}?(?:[AZ][1-9])?

This one allows 30 characters or 32 characters (ie if 31st is present then 32nd is required). 这个允许30个字符或32个字符(即如果存在31个字符则需要32个字符)。

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

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