Search code examples
regexbackreference

How to negate backreference regex


I'm making a regular expression to validate a password with the following requisites:

Have at least 6 characters.
Only have alphanumeric characters.
Don't have the same initial and ending character.

I thought about making it so that the first and last character match and then I would negate the backreference. My issue lies on how to negate that backreference. I looked for something stuff online but nothing worked. Here's what I got so far:

([\w])[\w]{3}[\w]+\1 //Generates a password with at least 6 chars in which the first and final characters match

Solution

  • You can use this regex:

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

    RegEx Demo

    • (?!.*\1$) will make sure first and last characters are not same.
    • [0-9a-zA-Z]{5,} will make sure length is at least 6 and there are only alpha-numeric characters in input.