Search code examples
phpregexpcre

PCRE Regex non-consecutive repeating


I'm trying to have a 6 character minimum, up to 15 chars total. First has to be alphanumeric (no special), next (up to) 13 to be alphanumeric and can include NON CONSECUTIVE (and only one of the following at a time) underscore OR period OR hyphen, then last character has to be alphanumeric.

example of okay: A_3.hj_3J

example not okay: F__3d66.K

example not okay: 6-_sd.6h9

This is what I have so far, I feel like it's close but annoyingly off. What am I doing wrong?

^[a-zA-Z0-9]{1}([_.-]?[a-zA-Z0-9])\S{4,13}[a-zA-Z0-9]{1}$

Solution

  • There are couple of problems:

    1. Your regex pattern will also match an input of more than 15 characters.
    2. Your regex will also other non-allowed characters in the middle like @ or # due to use of \S

    You can fix it by using a negative lookahead to disallow consecutive occurrence of period/hyphen/underscore and remove \S from middle of regex that allows any non-space character

    ^[a-zA-Z0-9](?!.*[_.-]{2})[\w.-]{4,13}[a-zA-Z0-9]$
    

    RegEx Demo