How to find two consecutive repeating characters in RGB using Regex?

Viewed 58

I am trying to find all RGB numbers, that have 2x3 consecutive numbers. By that, I mean this sort of numbers:

\#00FF11
\#66AA44
\#FF0000

I have tried writing this:

\b#(([0-9a-zA-Z])\1){3}\b

but that doesn't work.

Where is the problem? I would probably say, that the problem is somewhere around the \1, because it's the only part I am not so sure about.

1 Answers

The \1 pattern is a backreference to the Capturing group 1, i.e. (([0-9a-zA-Z])\1). You actually want to refer to Capturing group 2 and thus need \2 instead of \1.

Note that \b# will only match # that is preceded with a word char (letter, digit or _). You need to use a non-word boundary at the start, \B.

To match hex chars, [A-Fa-f] is preferable rather than [A-Za-z].

Use

@"\B#(?:([0-9a-fA-F])\1){3}\b"

Using the verbatim string literal, you do not need to double escape backslashes here.

Related