Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex for splitting CSS border attribute into its parts

Tags:

c#

regex

css

I want to split a border attribute from CSS into its constituent parts i.e:

.someClass{
  border: 1px solid black;
}

Into

border-width: 1px
border-style: solid;
border-color: black;

I have split off the border: and semi-colon before this, so I simply need to parse the value section of the attribute

Now in CSS you can have any combination of the 3 above attributes present so

border: 1px solid;
border: solid Gold;
border: 1em;
border: 1mm #000000;
border: 1px inset rgb(12, 44, 199);

All are legal so I need to account for that.

What I have so far is

([0-9]+[a-zA-Z|%]+)* *([a-zA-Z]*) *( .*)

Which works fine for the normal case, but fails on the "1px Solid" case as Solid is put into the 3rd capturing group, not the 2nd. I am not a regex expert so I may be making very basic mistakes, but any help would be greatly appreciated. I am working with C# (but have mainly been testing in http://gskinner.com/RegExr/ so any differences might have been the problem)

like image 654
Nymain Avatar asked Feb 05 '13 23:02

Nymain


1 Answers

Simply including border: at the start of the expression seems to be a major help since it won't accidentally match the second or third group. Similarly, adding ; to the end of the expression prevents capture of the second or third group too early. Other than that, changing the second group from * to + also helps because that allows it to match the second group as intended rather than the third. Altogether, try this:

border: ([0-9]+[a-zA-Z|%]+)* *([a-zA-Z]+)* *( .*)*;

I doubt that this is perfect and if you need results to work 100%, you probably should not use a single regular expression but instead tokenize and parse the string (I highly doubt CSS rules are parsed entirely with regex), but if this works for the limited rules you need it for then great.

like image 90
Explosion Pills Avatar answered Oct 04 '22 19:10

Explosion Pills