3

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
GRoutar
  • 1,311
  • 1
  • 15
  • 38
  • According to this thread - http://stackoverflow.com/questions/8055727/negating-a-backreference-in-regular-expressions - you'll want to use negative lookahead to negate the backreference. Just FYI, your regex will work for exactly 6 characters, but not at least six characters. Your `{3}` should be `{3,}` or even `{4,}` (you can remove that last `[\w]`. Also, you need not put `\w` inside square brackets, and it will allow non-alphanumerics (in this case, the underscore `_`). – David Faber Jan 08 '15 at 18:44

2 Answers2

3

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.
anubhava
  • 761,203
  • 64
  • 569
  • 643
  • It does work, but I have no idea why this (?!.*\1$) makes the initial and final chars different. – GRoutar Jan 08 '15 at 22:10
  • 1
    It's a negative lookahead - it makes sure that the last character is not the same as the one captured in the first group. – David Faber Jan 08 '15 at 22:13
  • `(?!.*\1$)` is a **negative lookahead** that means fail the match if last character is same as first character. – anubhava Jan 08 '15 at 22:14
  • Ok so this is pretty much a template such as (?!.*$) ? I was trying to understand char by char so I could somehow pull it off myself – GRoutar Jan 08 '15 at 22:25
2

use this pattern

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

Demo

alpha bravo
  • 7,838
  • 1
  • 19
  • 23