2

I've an XML file containing (among a lot of other stuff) hexadecimal color codes. I want to inspect all such codes that result in shades of grey. The pattern is

  • a hash tag (#) then
  • [a-fA-F0-9] repeated exactly 3 or 6 times
  • [^a-fA-F0-9]

So it should match #eee, #EEEEEE, #333333 but not #00006d, #123456 and so on. Regarding the regex flavor, it should ideally work in Notepad++, if that's no option then Python 2.7 is an alternative.

I tried using the backreference operator I found here. So far, my best attempt is

#([0-9a-fA-F])\1{3}[^0-9a-fA-F]

but I'm having some troubles:

  • It seems I should replace {3} by {2} for matching exactly three repetitions but I don't see why
  • I'm clueless as to how to match 6 repetitions as well. I think that {3,6} should match 3, 4, 5 or 6 repetitions but how can I exclude 4 and 5 repetitions? I thought about #([0-9a-fA-F])\1{3}[^0-9a-fA-F]|#([0-9a-fA-F])\1{6}[^0-9a-fA-F] but there must be a less ugly syntax for that, right?
Community
  • 1
  • 1
RubenGeert
  • 2,902
  • 6
  • 32
  • 50
  • this is not what regular expressions are for, you should convert the values to actual numbers and compare the ranges that way. –  Sep 12 '16 at 18:34
  • [*Some people, when confronted with a problem, think “I know, I'll use regular expressions.” Now they have two problems.* - Jamie Zawinski](http://regex.info/blog/2006-09-15/247) –  Sep 12 '16 at 18:34

2 Answers2

2

You can use thie regex:

#([0-9A-Fa-f])([0-9A-Fa-f])((?=\2)\1|(?:\1\2){2})\b

RegEx Demo

This should work on PCRE or on Python as well.

anubhava
  • 761,203
  • 64
  • 569
  • 643
-2

#([0-Fa-f][0-Fa-f])(\1{2}|\1{5})\b

Matches #AAA, #AAAAAA and also #ABABAB type grays.

BTW, [0-Fa-f] is identical to [0-9a-fA-F].

Edit: I am rong.

brentonstrine
  • 21,694
  • 25
  • 74
  • 120
  • 2
    No `[0-Fa-f]` is not identical to `[0-9a-fA-F]` `[0-F]` also matches `:`, `:` etc – anubhava Sep 12 '16 at 18:50
  • 1
    And your regex also allows `#EEEEEEEEEEEE` as valid input. – anubhava Sep 12 '16 at 19:00
  • Lol whoops. Nice catch there. Er, catches. :D – brentonstrine Sep 12 '16 at 19:16
  • 2
    Just delete your answer instead of editing in "I am rong [sic!]" – bwoebi Sep 12 '16 at 19:18
  • It's still a helpful answer for some people. It worked in my case since I don't have any #AAAAAAAAAAAA patterns, and it catches grays that the other one doesn't. Despite being "rong" my answer will probably be more helpful to most people in most situations, especially since I've indicated that there are problems with my answer so that people can read the comments and see the details. – brentonstrine Sep 13 '16 at 00:45