Petrus K.
Petrus K.

Reputation: 840

Regex matching reoccurrence of same literal

I'm trying to match the following values that repeat and are preceded with : and succeeded with ;:

border-radius:5px;
border-radius:4px 4px;
border-radius:8px 8px 8px;
border-radius:5px 5px 5px 5px;

The matching pattern shouldn't match the following:

border-radius:5px 0px;
border-radius:5px 0px 10px;
border-radius:5px 10px 8px 2px;

So far I know how to match everything before ':' and after ';':

(?<=:)(.+px)((?=;)|)

Also, I'm matching specific literals this way:

((5px)(\s)*){1,4}

But I want to be able to match a literal and then see if that exact same literal repeats 0 to 3 times separated with space and terminated with a semicolon.

I'm looking for something like: "If the first value is 5px then check if the following values are also 5px until a semicolon occurs."

Upvotes: 1

Views: 106

Answers (2)

anubhava
anubhava

Reputation: 785481

You can use this regex to validate repeats:

:(\d+px)(?:\h+\1)*;

RegEx Demo

Explanation: (with help from OP)

(?:\h+\1)*; starts a new non-capturing group, \h+ matches one or more horizontal white-spaces (such as tabs or regular space), \1 matches the occurrence of the first capture group, it seems to do so only when the match is exactly the same value as the first capture group (so 5px won't match with 8px for example). Finally * asserts that this non-capture matching occurs 0 to infinite amount of times (so no upper limit for 4 value).

Upvotes: 1

James Buck
James Buck

Reputation: 1640

You could try something like the following:

:\s*(\d+)\w*(?:\s+\1\w*)+;

Adjust the capturing group depending on your needs.

Regex demo

Upvotes: 0

Related Questions