Ram Patra
Ram Patra

Reputation: 16674

Regular expression to match source data like 7px 7px 7px 7px?

I need a regular expression which would do the following -->

For example,

margin:7px 7px 7px 7px;

Should be compressed to -->

margin:7px;

(NOTE: The number may not be only 7,it can be any number. And the units can be in px|em|%|in|cm|mm|pc|pt|ex)

Upvotes: 1

Views: 165

Answers (3)

Naveed S
Naveed S

Reputation: 5256

Replace (\d+(px|em|%|in|cm|mm|pc|pt|ex))\s+\1\s+\1\s+\1 with $1

\d+ matches one or more digits (px|em|%|in|cm|mm|pc|pt|ex) matches any one of mentioned units \s+ matches one or more whitespaces (for matching separation between each occurrence) \1 matches the first capture group i.e. the digits followed by units (4 times \1 requires 4 occurrences of digits+units)

For allowing decimal part also, use (\d+(.\d+)?(px|em|%|in|cm|mm|pc|pt|ex))\s+\1\s+\1\s+\1

Replacing with $1 replaces the matched input with first capture group

Upvotes: 1

leftclickben
leftclickben

Reputation: 4614

This is definitely possible in the specific case of being repeated 4 times.

Using backreferences, this is possible for a particular value of n the number of times the number is repeated. In your case, n = 4.

This one matches any "unit" value made up of only alpha characters, i.e. "px", "em" or "foo", plus the special case "%". It could be made more restrictive to particular units by replacing \w* with a more specific match like (?:em|px|......)

/^(\d+(?:\.\d+)?(?:\w*|%))\s+\1\s+\1\s+\1$/

For example:

// first four examples all match
echo preg_match('/^(\d+(?:\.\d+)?(?:\w*|%))\s+\1\s+\1\s+\1$/', '7px 7px 7px 7px');
1

echo preg_match('/^(\d+(?:\.\d+)?(?:\w*|%))\s+\1\s+\1\s+\1$/', '7em 7em 7em 7em');
1

echo preg_match('/^(\d+(?:\.\d+)?(?:\w*|%))\s+\1\s+\1\s+\1$/', '5px 5px 5px 5px');
1

echo preg_match('/^(\d+(?:\.\d+)?(?:\w*|%))\s+\1\s+\1\s+\1$/', '7% 7% 7% 7%');
1

echo preg_match('/^(\d+(?:\.\d+)?(?:\w*|%))\s+\1\s+\1\s+\1$/', '5.2cm 5.2cm 5.2cm 5.2cm');
1

// different value, no match
echo preg_match('/^(\d+(?:\.\d+)?(?:\w*|%))\s+\1\s+\1\s+\1$/', '5px 5px 5px 7px');
0

// not 4 elements, no match
echo preg_match('/^(\d+(?:\.\d+)?(?:\w*|%))\s+\1\s+\1\s+\1$/', '7px 7px 7px');
0

// different unit, no match
echo preg_match('/^(\d+(?:\.\d+)?(?:\w*|%))\s+\1\s+\1\s+\1$/', '7em 7em 7em 7px');
0

Upvotes: 2

Niklas
Niklas

Reputation: 4223

Probably you are not asking for the special case 7, but for any number, where all four are the same. One can prove, that there is no such regular expression.

Upvotes: 1

Related Questions