Regex to match repeating characters

var R = /([^])\1+/g

I’ve found that this regular expression R is used to match repeating characters in a string.

e.g “HazzzeLLllnut$$$”.match(R) returns [“zzz”,“LL”,“ll”,"$$$"]

I can’t see how it does this? When I omit the \1+, so that the expression becomes
var R = /[^]/g
It matches every individual character in a string. I understand that the caret ^ in square brackets ([^]) means “not the following”? How does this regex work exactly and how is it matching every character?

Easier to let a Regex tester explain it…

regex101: build, test, and debug regex

Select the ECMAScript flavor and paste the pattern without the delimiters/switches, then in the string section, the string with no quotes. Read the explanation in the top right, and the matches below that.

The above has your pattern already saved so you shouldn’t have to do anything but read the explanation.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.