简体   繁体   English

正则表达式中的最小长度

[英]Minimum length in regular expression

I am well aware that to indicate a minimum length for a regular expression one should use this quantifier, if a min of say 4 characters is wanted {4,}我很清楚,要指示正则表达式的最小长度,应该使用此量词,如果需要至少 4 个字符{4,}

I am trying to compile a regex in go that will allow我正在尝试在go中编译一个正则表达式,它将允许

  • a min of 4 chars in total , including the hyphen总共至少 4 个字符,包括连字符

  • only letters digits and hyphens只有字母数字和连字符

  • last character should not be a hyphen最后一个字符应该是一个连字符

So it was suggested that I use this:所以有人建议我使用这个:

^[a-zA-Z0-9-]*[a-zA-Z0-9]$

which seems to do the job.这似乎可以完成这项工作。

Now, given that I want to enforce a min of 4 chars, I modified it a bit as follows:现在,考虑到我想强制执行最少 4 个字符,我对它进行了如下修改:

^[a-zA-Z0-9-]*[a-zA-Z0-9]{4,}$

However this does not seem to do the work given that the pattern below然而,鉴于下面的模式,这似乎并没有完成工作

eee0-lll

does not match (according to my requirements it should).匹配(根据我的要求,它应该)。

One of the constraints I am faced with is that go does not allow for lookaround assertions.我面临的限制之一是go不允许环视断言。

You can use您可以使用

^[a-zA-Z0-9-]{4,}\b$

See the regex demo查看正则表达式演示

Details细节

  • ^ - start of string ^ - 字符串的开始
  • [a-zA-Z0-9-]{4,} - four or more ASCII letters, digits or hyphens - \\b - a word boundary that requires a word char (letter, digit or _ ) to appear immediately to the left of the current position because the next pattern requires... [a-zA-Z0-9-]{4,} - 四个或更多 ASCII 字母、数字或连字符 - \\b - 需要字字符(字母、数字或_ )立即出现在左侧的字边界当前位置,因为下一个模式需要...
  • $ - end of string. $ - 字符串的结尾。

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

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