2012-04-14 129 views
0

我有字符串的CSS屬性和值:正則表達式與CSS屬性

str = "filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#cccccc', endColorstr='#000000'); 
     background: -webkit-linear-gradient(top, black, white); 
     animation-duration: 12s;"; 

,我想我的比賽只返回特性

properties = text.match(/[^;:]*:/g); 

,但它也返回「進程id」,我怎樣才能避免它?

+0

你在做什麼?根據不同,使用CSS解析器或僅查詢元素集樣式屬性可能會更好。 – Esailija 2012-04-14 15:17:33

回答

1

搜索線或「的開始; 「以及(或可能取決於你的字符串格式化一個斷行/片):

/(^|;)[^:;]*:/ 

你仍然需要清理你的結果有點雖然。

或者,您可以將字符串拆分爲「;」第一,然後分裂中對每一位「:」搶各的0號成員的屬性:

var str = "filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#cccccc', endColorstr='#000000');background: -webkit-linear-gradient(top, black, white);animation-duration: 12s;"; 

var rules = str.split(";") 

var i, l = rules.length; 

var properties = []; 

for(i = 0; i < l; i++){ 
    properties.push(rules[ i ].split(":")[0]); //dangerous if you're not sure you'll always have a result 
} 
0

請嘗試

properties = text.match(/^[^;:]*:/g); 

編輯: 這裏是一個更好的解決方案提供總有屬性和值之間的空間:

properties = text.match(/[^ ;:]+(?=:)/g) 
+0

僅當每行在其結尾處具有實際行返回時才起作用。由於休息前沒有「\」,因此不確定是這種情況。 – webnesto 2012-04-14 15:30:39

0

爲了避免空規則,當你分割上結束串半,

分裂半內容跟隨他們;

var rules= str.split(/;(?=\S+)/); 

for(var i= 0, L= rules.length; i<L; i++){ 
    rules[i]= rules[i].split(':')[0]; 
} 

/* 
alert(rules)>>(Array) 
filter, background, animation-duration 
*/