Hex color regex
Matches CSS hex colours of three or six digits after a #. The trailing word boundary stops it matching the first three digits of a longer token.
The pattern
//gi
Sample text, 3 matches
Palette: paper #f3f4f2, ink #16181c, accent #2f3fd0, and #abcd is not a 3 or 6 digit colour.
What it deliberately doesn’t do
- Four- and eight-digit colours with alpha (#rgba, #rrggbbaa) are not included.
- It will also match a # followed by hex in non-CSS text, such as an issue number like #123.
Explained, in order
#Matches the character '#' literally(?:[0-9a-fA-F]{3}|[0-9a-fA-F]{6})Non-capturing group — groups the pattern without capturing[0-9a-fA-F]{3}|[0-9a-fA-F]{6}Alternation — matches any ONE of the 2 alternatives listed above/below[0-9a-fA-F]Character class — matches one character from: '0' through '9', 'a' through 'f', 'A' through 'F'{3}The preceding element matches exactly 3 times (greedy)[0-9a-fA-F]Character class — matches one character from: '0' through '9', 'a' through 'f', 'A' through 'F'{6}The preceding element matches exactly 6 times (greedy)\bWord boundary — asserts a boundary between a word character and a non-word character. Consumes no characters.
In your language
JavaScript
The engine this page was tested with.
const re = /#(?:[0-9a-fA-F]{3}|[0-9a-fA-F]{6})\b/gi;
// Example
const matches = [...str.matchAll(/#(?:[0-9a-fA-F]{3}|[0-9a-fA-F]{6})\b/gi)];
for (const m of matches) {
console.log(m[0], m.index, m.groups);
}Python
Translated. Named groups are rewritten to (?P<name>…).
import re
pattern = re.compile(r"#(?:[0-9a-fA-F]{3}|[0-9a-fA-F]{6})\b", re.IGNORECASE)
# Example
for m in pattern.finditer(text):
print(m.group(0), m.start(), m.groups())Go
Translated. Go's RE2 has no lookaround or backreferences.
package main
import (
"fmt"
"regexp"
)
// Note: Inline flags at the start of the pattern: (?i), (?m), (?s).
var re = regexp.MustCompile(`(?i)#(?:[0-9a-fA-F]{3}|[0-9a-fA-F]{6})\b`)
func main() {
for _, match := range re.FindAllStringSubmatch(text, -1) {
fmt.Println(match[0], match)
}
}Rust
Translated. The regex crate has no lookaround or backreferences.
use regex::Regex;
// Note: Rust finds all matches via find_iter / captures_iter (no 'g' flag).
fn main() {
let re = Regex::new(r#"(?i)#(?:[0-9a-fA-F]{3}|[0-9a-fA-F]{6})\b"#).unwrap();
for m in re.find_iter(text) {
println!("{} at {}", m.as_str(), m.start());
}
}