简体   繁体   English

使用正则表达式验证特定字符的字符串和精确长度的数字

[英]Validate a string of certain characters and numeric of exact length using Regex

Objective :match exact 10 of mixed uppercase characters (except I,O, and space) and numeric from 2 to 9:目标:精确匹配 10 个混合大写字符(I、O 和空格除外)和 2 到 9 的数字:

To be exact, here is the valid set the value must be coming from:确切地说,这是值必须来自的有效集合:

{'2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J', 'K','L', 'M', 'N', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'} {'2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', ' E', 'F', 'G', 'H', 'J', 'K', 'L', 'M', 'N', 'P', 'Q', 'R', 'S' , 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'}

I have tried this:我试过这个:

^[A-Z2-9][^IO01a-z ]{10}$

But this 11 length would pass: 9PAUUH98TYE while 10 of them wouldn't pass 9PAUUH98TY但是这 11 个长度会通过:9PAUUH98TYE 而其中 10 个不会通过 9PAUUH98TY

I also tried:我也试过:

\b[A-Z2-9][^IO01a-z ]{10}\b

So you could do some fancy negative lookaround magic , but really, just listing out the letters you expect is fine.所以你可以做一些花哨的负面环视魔术,但实际上,只列出你期望的字母就可以了。

^[ABCDEFGHJKLMNPQRSTUVWXYZ2-9]{10}$

Using spanning, it can be shortened to使用跨度,它可以缩短为

^[A-HJ-NP-Z2-9]{10}$

This is the """lazy""" method, but it will work consistently the same across all regex flavors.这是 """lazy""" 方法,但它在所有正则表达式风格中的工作方式一致。 Negative lookbehinds sometimes might behave differently in .Net vs JavaScript vs others, for example.例如,在 .Net、JavaScript 和其他中,负面的后视有时可能表现不同。

Also, it's SUPER important to use ^ and $ in your pattern.此外,在您的模式中使用^$非常重要。 They will help to ensure that the whole input string is the correct number of characters.它们将有助于确保整个输入字符串的字符数正确。

You can use negative lookahead/lookbehind to exclude the set you don't want:您可以使用负前瞻/后视排除您不想要的集合:

\b([A-Z2-9](?<![IO])){10}\b

Check here to see the test cases在这里查看测试用例

Would this work?这行得通吗?

\b[A-HJ-NP-Z2-9]{10}\b

Demo演示

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

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