Skip to content

Regex for Css Color Rgb — Pattern, Examples & Caveats

Pattern
^rgba?\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*(,\s*(0|1|0?\.\d+)\s*)?\)$

This pattern matches CSS rgb() and rgba() color functions, capturing the three channel values and an optional alpha. It validates the syntax shape but not whether each channel is within 0-255. Web patterns deal with markup, styling and web identifiers: HTML tags and comments, CSS colors, Markdown links, slugs and source-code comments. They are handy for quick scanning and lightweight transforms, but markup is not a regular language, so anything structural or security-sensitive should use a real parser (DOM, CSS or Markdown) rather than regex alone. It needs no special flags. Apply it to the whole input as a format contract. It accepts channel values up to 999 because \d{1,3} is not range-checked; clamp or validate 0-255 in code, or use a stricter alternation. Modern CSS allows space-separated channels and percentage values (rgb(255 0 0 / 50%)) which this comma-based pattern rejects. Alpha is limited to 0, 1 or a simple decimal; percentages and other forms need extension. As with any regular expression, confirm its behavior in your target engine, test boundary and adversarial inputs, and watch for catastrophic backtracking before relying on it in production.

Advertisement
Ad slot · ref-top

Token-by-token explanation

  • rgba?\( — rgb( or rgba( opening
  • \s*(\d{1,3})\s*, — a channel value with optional surrounding spaces, repeated three times
  • (,\s*(0|1|0?\.\d+)\s*)? — optional alpha: 0, 1 or a decimal
  • \) — closing parenthesis
  • ^...$ — anchors spanning the function

What it matches

rgb(255, 0, 0)rgba(0,0,0,0.5)rgb( 12 , 34 , 56 )rgba(255,255,255,1)

What it does not match

rgb(255,0)hsl(0,100%,50%)rgb(1,2,3,4)rgb()not a color

When to use it

Reach for a web pattern for quick scanning and lightweight transforms of markup, styling and web identifiers: locating tags, comments, colors, slugs or Markdown links. For anything structural or security-sensitive — parsing a DOM, sanitizing HTML, rewriting CSS — use a real parser or a proven library instead, because markup is not a regular language and regex-based handling is a frequent source of bugs and cross-site scripting bypasses.

Caveats

  • It accepts channel values up to 999 because \d{1,3} is not range-checked; clamp or validate 0-255 in code, or use a stricter alternation.
  • Modern CSS allows space-separated channels and percentage values (rgb(255 0 0 / 50%)) which this comma-based pattern rejects.
  • Alpha is limited to 0, 1 or a simple decimal; percentages and other forms need extension.

Code examples

JavaScript
const re = /^rgba?\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*(,\s*(0|1|0?\.\d+)\s*)?\)$/;
const input = "rgb(255, 0, 0)";
if (re.test(input)) {
  // valid: proceed
} else {
  // reject with a helpful message
}
Python
import re

rx = re.compile(r"^rgba?\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*(,\s*(0|1|0?\.\d+)\s*)?\)$")
value = "rgb(255, 0, 0)"
if rx.fullmatch(value):
    pass  # valid
else:
    raise ValueError("invalid format")
Java
import java.util.regex.*;

Pattern p = Pattern.compile("^rgba?\\(\\s*(\\d{1,3})\\s*,\\s*(\\d{1,3})\\s*,\\s*(\\d{1,3})\\s*(,\\s*(0|1|0?\\.\\d+)\\s*)?\\)$");
Matcher m = p.matcher("rgb(255, 0, 0)");
boolean ok = m.matches();   // whole input must conform
PHP
<?php
$subject = "rgb(255, 0, 0)";
if (preg_match('/^rgba?\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*(,\s*(0|1|0?\.\d+)\s*)?\)$/', $subject, $m)) {
    // $m[0] is the full match
}

How to test it

Before trusting any pattern, test it against three kinds of input: valid examples that must match, invalid examples that must be rejected, and edge cases at the boundaries (empty strings, maximum lengths, unusual separators and Unicode). Paste the expression into a live regex tester with your actual sample data and confirm the highlighted matches are exactly what you intend. Watch for catastrophic backtracking by trying long non-matching inputs, and remember that engine differences (JavaScript, Python, Java, PCRE, Go/RE2) mean a pattern that works in one may fail or behave differently in another — especially lookarounds, which Go's RE2 does not support at all.

Frequently asked questions

Does it validate the 0-255 range?

No — \d{1,3} matches 0-999. Add a range alternation like (25[0-5]|2[0-4]\d|1?\d?\d) per channel, or validate numerically after matching.

Why does it reject rgb(255 0 0)?

That is the modern CSS Color 4 space-separated syntax. This pattern targets the legacy comma-separated form; extend it to support both if needed.

When should I avoid regex for web content?

For parsing HTML, CSS or Markdown structure, use a real parser. Regex cannot handle nesting, quoted delimiters or malformed markup reliably, and regex-based sanitization is a common source of XSS bypasses.

Why is regex HTML sanitization dangerous?

HTML has nested, quoted and malformed constructs that regex mis-parses, so attackers hide scripts in forms the pattern misses. Always sanitize with a proven library (DOMPurify) or a real parser, never ad-hoc regex.

Advertisement
Ad slot · ref-in-article

Try the Regex Tester

Live regex matching with groups, flags and explanations.

Open tool →