简体   繁体   English

至少一个带有现有正则表达式的数字

[英]At least one number with existing regex

My conditions...我的条件...

  1. Alpha-Numeric value字母数字值
  2. Only one space or hyphen is allowed只允许一个空格或连字符
  3. Must contain at least one number必须包含至少一个数字
  4. Cannot start or end with space or hyphen不能以空格或连字符开头或结尾
  5. Minimum 2 characters, maximum 16 characters excluding space/hyphen最少 2 个字符,最多 16 个字符,不包括空格/连字符

As of now I prepared the regex截至目前,我准备了正则表达式

^(?=.{2,16}$)([a-zA-Z\d]+)([\s^\-]|[\-^\s]|[a-zA-Z\d]*)([a-z[A-Z\d]+)

Its only missing 3rd point.它唯一缺少的第三点。

Test strings Valid测试字符串有效

"test one"
"test 2two"
"test3 three222"
"3test-4four"

Invalid无效的

"-test"
"test-d f"

You may use this regex with 2 lookahead conditions:您可以将此正则表达式与 2 个前瞻条件一起使用:

^(?=(?:[a-zA-Z\d][ -]?){2,16}$)(?=[^\d\n]*\d)[a-zA-Z\d]+(?:[ -][a-zA-Z\d]+)?$

RegEx Demo正则表达式演示

PS: Note that test one is an invalid string as it doesn't have any digit. PS:请注意, test one无效字符串,因为它没有任何数字。

RegEx Details:正则表达式详细信息:

  • ^ : Start ^ : 开始
  • (?=(?:[a-zA-Z\d][ -]?){2,16}$) : Positive Lookahead to make sure we have 2 to 16 length of alphanumeric characters (?=(?:[a-zA-Z\d][ -]?){2,16}$) :正向预测以确保我们有 2 到 16 个长度的字母数字字符
  • (?=\D*\d) : Positive Lookahead to make sure we have at least one digit (?=\D*\d) :正向前瞻以确保我们至少有一位数字
  • [a-zA-Z\d]+(?:[ -][a-zA-Z\d]+)? : Match any test that starts with alphanumeric, optionally followed by a single space or hyphen and ends with alphanumeric :匹配任何以字母数字开头的测试,可选地后跟一个空格或连字符并以字母数字结尾
  • $ : End $ : 结束

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

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