Regex to find 2 identical characters at the end of a string

I need to find a regular expression with the following rules.

  • contains 8 to 20 characters (regular or normal).
  • contains no whitespace characters.
  • cannot start with a number (0-9) or an underscore (_).
  • at the end of the string, which should be 2 of the same char.
  • must contain at least 1 number.

OK

+234567899
a_1de*Gg
xy1Me*__
!41deF_hij2lMnopq3ss
C234567890123$^67800
*5555555
sDF564zer""
!!!!!!!!!4!!!!!!!!!!
abcdefghijklmnopq9ss

      

Out of order:

has more or less 8-20 characters:

a_1+Eff
B41def_hIJ2lmnopq3stt
abCDefghijklmnopqrss5

      

has whitespace characters:

A_4 e*gg

      

starts with a number or underscore:

__1+Eff
841DEf_hij2lmnopq3stt

      

ends with two different characters:

a_1+eFg
b41DEf_hij2lmnopq3st

      

does not contain numbers:

abCDefghijklmnopqrss
abcdef+++dF
!!!!!!!!!!!!!!!!!!!!

      

As long as I have it

((?m:[^0-9_]^(?=.*[0-9])\S{8,20}$))

      

But I can't figure out the two same characters at the end?

+3


source to share


2 answers


For most regex variants (PCRE, Python, PHP, JavaScript) the following will work:

/^(?=\S{8,20}$)(?=\D*\d)(?![0-9_]).{6,18}?(.)\1$/i

      

Demonstration with unit tests versus your example cases



Explanation:

  • /

  • ^

    start of line
  • (?=\S{8,20}$)

    followed by 8-20 characters without spaces.
  • (?=\D*\d)

    contains a digit
  • (?![0-9_])

    cannot start with a number or underscore
  • .{6,18}?

    Unwanted character match (moves us from the beginning of the line to the end)
  • (.)\1

    match any character followed by the same character again
  • $

    end of line
  • /

  • i

    flag: case insensitive (required to see Gg

    , for example, the same character twice)
+9


source


The following should suit your needs:

^(?=.*\d)[\D\S]\S{5,17}(\S)\1$

      

Regular expression visualization



visualization Debuggex

Demo on regex101

+1


source







All Articles