Regular expression to split CSS border attribute into parts

I want to break the border attribute from CSS into its component parts. ie:

.someClass{ border: 1px solid black; } 

IN

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

I split the border: and half a year before, so I just need to parse the attribute value section

Now in CSS you can have any combination of the three attributes above to

 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 consider this.

What am i still

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

Which is great for the normal case, but it doesn’t work in the case of β€œ1px Solid,” since Solid is placed in the 3rd capture group, not the 2nd. I am not a regular expression expert, so I can make very simple mistakes, but any help would be greatly appreciated. I work with C # (but mostly tested http://gskinner.com/RegExr/ , so any differences could be a problem)

+6
source share
1 answer

Just including border: at the beginning of an expression seems like serious help, since it will not accidentally coincide with the second or third group. Similarly, the addition ; the end of the expression prevents the capture of the second or third group too early. In addition, changing the second group from * to + also helps, because it allows her to map the second group for its intended purpose, rather than the third. In general, try the following:

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

I doubt this is perfect, and if you want the results to work 100%, you probably shouldn't use one regex, and instead use tokenization and parse the string (I highly doubt CSS rules are fully parsed using regular expressions), but if that works for the limited rules that you need it for, then fine.

+1
source

All Articles