Home > other >  regex matching consecutive characters from start and end
regex matching consecutive characters from start and end

Time:04-22

Im trying to match a string to that containsthree consecutive characters at the beginning of the line and the same six consecutive characters at the end. for example BBB i love regex BBBBBB the B's would be highlighted from search

I have found a way to find get the first 3 and the last six using these two regex codes but im struggling to combine them ^([0-9]|[aA-zZ])\1\1 and ([0-9]|[aA-zZ])\1\1\1\1\1$ appreciate any help

CodePudding user response:

If you want just one regular expression to "highlight" only the 1st three characters and last six, maybe use:

(?:^([0-9A-Za-z])\1\1(?=.*\1{6}$)|([0-9A-Za-z])\2{5}(?<=^\2{3}.*)$)

See an online demo


  • (?: - Open non-capture group to allow for alternations;
    • ^([0-9A-Za-z])\1\1(?=.*\1{6}$) - Start-line anchor with a 1st capture group followed by two backreferences to that same group. This is followed by a positive lookahead to assert that the very last 6 characters are the same;
    • | - Or;
    • ([0-9A-Za-z])\2{5}(?<=^\2{3}.*)$ - The alternative is to match a 2nd capture group with 5 backreferences to the same followed by a positive lookbehind (zero-width) to check that the first three characters are the same.

Now, if you don't want to be too strict about "highlighting" the other parts, just use capture groups:

^(([0-9A-Za-z])\2\2).*(\2{6})$

See an online demo. Where you can now refer to both capture group 1 and 3.

  • Related