Regex to check for at least 3 characters?

前端 未结 4 1044
太阳男子
太阳男子 2020-12-06 16:04

I have this regex to allow for only alphanumeric characters.

How can I check that the string at least contains 3 alphabet characters as well.

My current rege

相关标签:
4条回答
  • 2020-12-06 16:38

    This should do the work:

    ^([0-9]*[a-zA-Z]){3,}[0-9]*$

    It checks for at least 3 "Zero-or-more numerics + 1 Alpha" sequences + Zero-or-more numerics.

    0 讨论(0)
  • 2020-12-06 16:44

    You want to match zero or more digits then 3 consecutive letters then any other number of digits?

    /\d*(?:[a-zA-Z]){3,}\d*/

    0 讨论(0)
  • 2020-12-06 16:51

    + means "1 or more occurrences."

    {3} means "3 occurrences."

    {3,} means "3 or more occurrences."

    + can also be written as {1,}.

    * can also be written as {0,}.

    0 讨论(0)
  • 2020-12-06 16:54

    To enforce three alphabet characters anywhere,

    /(.*[a-z]){3}/i
    

    should be sufficient.

    Edit. Ah, you'ved edited your question to say the three alphabet characters must be consecutive. I also see that you may want to enforce that all characters should match one of your "accepted" characters. Then, a lookahead may be the cleanest solution:

    /^(?.*[a-z]{3})[a-z0-9]+$/i
    

    Note that I am using the case-insensitive modifier /i in order to avoid having to write a-zA-Z.

    Alternative. You can read more about lookaround assertions here. But it may be a little bit over your head at this stage. Here's an alternative that you may find easier to break down in terms of what you already know:

    /^([a-z0-9]*[a-z]){3}[a-z0-9]*$/i
    
    0 讨论(0)
提交回复
热议问题