Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex to find character only if it occurs 4 times

I'm stuck on making this Regex. I tried using look-ahead and look-behind together, but I couldn't use the capture group in the look-behind. I need to extract characters from a string ONLY if it occurs 4 times.

If I have these strings

  • 3346AAAA44
  • 3973BBBBBB44
  • 9755BBBBBBAAAA44

The first one will match because it has 4 A's in a row. The second one will NOT match because it has 6 B's in a row. The third one will match because it still has 4 A's. What makes it even more frustrating, is that it can be any char from A to Z occuring 4 times.

Positioning does not matter.

EDIT: My attempt at the regex, doesn't work.

(([A-Z])\2\2\2)(?<!\2*)(?!\2*)
like image 449
Styn Avatar asked Dec 18 '25 16:12

Styn


1 Answers

If lookbehind is allowed, after capturing the character, negative lookbehind for \1. (because if that matches, the start of the match is preceded by the same character as the captured first character). Then backreference the group 3 times, and negative lookahead for the \1:

`3346AAAA44
3973BBBBBB44
9755BBBBBBAAAA44`
.split('\n')
.forEach((str) => {
  console.log(str.match(/([a-z])(?<!\1.)\1{3}(?!\1)/i));
});
  • ([a-z]) - Capture a character
  • (?<!\1.) Negative lookbehind: check that the position at the 1st index of the captured group is not preceded by 2 of the same characters
  • \1{3} - Match the same character that was captured 3 more times
  • (?!\1) - After the 4th match, make sure it's not followed by the same character
like image 193
CertainPerformance Avatar answered Dec 20 '25 05:12

CertainPerformance



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!