如何否定反向引用正则表达式

时间:2015-01-08 18:37:53

标签: regex backreference

我正在制作一个正则表达式来验证具有以下必要条件的密码:

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

我考虑过这样做,以便第一个和最后一个角色匹配,然后我会否定反向引用。我的问题在于如何否定这种反向引用。我在网上搜索了一些东西,但没有任何效果。这是我到目前为止所得到的:

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

2 个答案:

答案 0 :(得分:2)

使用此模式

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

Demo

答案 1 :(得分:2)

您可以使用此正则表达式:

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

RegEx Demo

  • (?!.*\1$)将确保第一个和最后一个字符不相同。
  • [0-9a-zA-Z]{5,}将确保长度至少为6,并且输入中只有字母数字字符。
相关问题