Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 795
GRoutar Avatar asked May 27 '26 06:05

GRoutar


2 Answers

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.
like image 122
anubhava Avatar answered Jun 04 '26 07:06

anubhava


use this pattern

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

Demo

like image 25
alpha bravo Avatar answered Jun 04 '26 07:06

alpha bravo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!