Skip to main content
hank-builds.com

CSS Property regex

Matches CSS property-value pairs.

/([a-z-]+)\s*:\s*([^;]+);/g

What it matches

A property name of lowercase letters and hyphens, a colon with optional whitespace on either side, everything up to the terminating semicolon as the value, and the semicolon itself. The two groups hand back the declaration already split into name and value.

Railroad diagram

Read left to right. Every path through the diagram is a string the pattern accepts.

Group [a-z-] \s ":" \s Group [^;] ";"

Drag to pan. Ctrl+scroll to zoom.

Breakdown

gFind all matches instead of stopping after the first
[a-z-]+Match one of: Literal "a"–Literal "z", Literal "-", one or more
\s*Whitespace, zero or more
:Literal ":"
\s*Whitespace, zero or more
[^;]+Match not one of: Literal ";", one or more
;Literal ";"

Test cases

Matches

  • color: red;
  • background-color:#fff;
  • font-size : 16px;

Does not match

  • color red;
  • color: red

Caveats

The value class stops at the first semicolon, so a semicolon inside a quoted string or a data: URI cuts the match short. It misses custom properties, which start with --, and the final semicolon is required, so the last declaration in a block is skipped whenever it is omitted.

More web patterns

Test this against your own input in the regex tester, browse the full pattern library, or check the syntax cheat sheet.