简体   繁体   English

正则表达式匹配有限长度的字符串,如果存在数字,则不能超过 5 位

[英]Regex to match string of limited length and if number digit are present it can't be more than 5 digit

im looking for regex that can match string with requirement below.我正在寻找可以将字符串与以下要求匹配的正则表达式。

  • must be 5 to 15 characters必须是 5 到 15 个字符
  • Alphanumeric, can accept fully alphabet, if numeric are present, it must not exceed 5 digit and it can be in anywhere in the string.字母数字,可以接受全字母表,如果存在数字,则不能超过 5 位,并且可以位于字符串的任何位置。

Example accepted input接受的输入示例

  • helloworld你好,世界
  • 123helloworld56 123你好世界56
  • 1h2e3l4l5oworld 1h2e3l4l5oworld
  • 12345 12345

if the numeric digit exceeded 5 it shall be rejected.如果数字超过 5,则应拒绝。 Example rejected input:拒绝输入示例:

  • 123456 123456
  • 123hello4567 123你好4567

So far i have tried while looking online and done some tweaking, but none work as expected.到目前为止,我已经尝试在网上查找并进行了一些调整,但没有按预期工作。

^(?=.*\d?.*\d?.*\d?.*\d?.*\d?).{0,15}$
^(?=[a-zA-Z1-9]{5,15}$)[a-zA-Z]{1,15}[1-9]{0,5}$
^(?=.*\d){0,5}.{0,15}$

I have stuck on this for some time now, any help are appreciated!我已经坚持了一段时间了,任何帮助表示赞赏!

If there can not be more than 5 digits in total, that means you should not be able to match 6 digits.如果总共不能超过 5 位数字,则表示您应该无法匹配 6 位数字。

You can use a negative lookahead to assert what is on the right can not match 6 digits.您可以使用否定前瞻来断言右侧的内容无法匹配 6 位数字。

^(?!(?:[^\d\r\n]*\d){6})[a-zA-Z0-9]{5,15}$

Explanation解释

  • ^ Start of string ^字符串开始
  • (?! Negative lookahead, assert what is at the right is not (?!负前瞻,断言右边的不是
    • (?:[^\\d\\r\\n]*\\d){6} Match 6 times any char except a newline or a digit, then match a digit (?:[^\\d\\r\\n]*\\d){6}匹配 6 次除换行符或数字以外的任何字符,然后匹配一个数字
  • ) Close lookahead )关闭前瞻
  • [a-zA-Z0-9]{5,15} Match 5-15 times any of the listed in the character class [a-zA-Z0-9]{5,15}匹配 5-15 次字符类中列出的任何一个
  • $ End of string $字符串结尾

Regex demo正则表达式演示

Note that using [1-9] in a character class does not match the 0, and \\d will请注意,在字符类中使用[1-9]与 0 不匹配,并且\\d


About the patterns in the question关于问题中的模式

  • ^(?=.*\\d?.*\\d?.*\\d?.*\\d?.*\\d?).{0,15}$

Here, the lookahead will always be true as all the parts in it are optional.在这里,前瞻将始终为真,因为其中的所有部分都是可选的。 It could also match an empty string as the quantifier {0,15} starts at 0, which makes it optional.它也可以匹配一个空字符串,因为量词{0,15}从 0 开始,这使得它是可选的。

  • ^(?=[a-zA-Z1-9]{5,15}$)[a-zA-Z]{1,15}[1-9]{0,5}$

The pattern asserts a string with 5-15 times any of the listed in the character class.该模式断言一个字符串,它是字符类中列出的任何一个的 5-15 倍。 But the matching starts with 1-15 times a char a-zA-Z followed by matching 0-5 times a digit at the end of the string.但是匹配以字符 a-zA-Z 的 1-15 次开始,然后匹配字符串末尾的数字 0-5 次。

  • ^(?=.*\\d){0,5}.{0,15}$

The pattern optionally asserts 0-5 digits which is always true as it is optional.该模式可选地断言 0-5 位数字,这始终为真,因为它是可选的。 Then it matches 0-15 times any char.然后它匹配任何字符的 0-15 次。

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

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