2016-07-06 42 views
0

我有不好的CSS文件,像這樣的規則(我無法控制這些文件的生成),清理錯誤的CSS規則:嘗試使用js代碼

.class html { 
} 

.class2 html,.class3 html { 

} 

html { 

} 

html .class4 { 

} 

.class body { 
} 

.class2 body,.class3 body {  
} 

body {  
} 

body .class4 {  
} 

,你可以看到,一些HTML和BODY規則在類名後放

我想要做的是扭轉這個規則,以獲得適當的限定符(標籤然後類)。

我預期的結果是:

html .class { 
} 

html .class2 ,html .class3 { 

} 

html { 

} 

html .class4 { 

} 

body .class { 
} 

body .class2 ,body .class3 { 

} 

body { 

} 

body .class4 { 

} 

我試圖用一個正則表達式:([^,]+\s+)(html|body)這個換人:$2 $1,但我沒有得到我想要的東西。 (Repro on regex101

如何達到我的目標?

PS:這將以自定義吞嚥任務結束,因此需要js正則表達式解決方案。

+0

或者嘗試['(\。\ S +)( \ s +)(html | body)' - >'$ 3 $ 2 $ 1'](https://regex101.com/r/kM9kZ7/2)。 –

+0

@Tushar:只關注body和html標籤;因爲它們更高在dom比我的根類; –

+0

@WiktorStribiżew:這工作。你應該添加一個答案,所以我可以獎勵你 –

回答

2

您可以使用

(\.\S+)(\s+)(html|body) 

$3$2$1取代。

正則表達式演示是here

表達細節

  • (\.\S+) - 字面點,接着與一個或多個非空白字符(第1組)
  • (\s+) - 的一個或多個空格(組2)
  • (html|body) - 或者htmlbody文字字符序列(組3)。

替換模式包含反向交換髮生的組反向引用。

爲了考慮像.class .classN html案件,使用

/(\.\S+(?:\s+\.\S+)*)(\s+)(html|body)/g 

其中非捕獲組(?:\s+\.\S+)**((零次或多次量化)。

+0

完美地工作。作爲一個方面說明,在我的大文件中,我把'.pipe(替換(/(\。\ S +)(\ s +)(html | body)/ g,'$ 3 $ 2 $ 1'))//調整規則順序(html和包括這個調整。 –

+0

嗡嗡聲,在我的情況下,實際上不是一個問題,但如果兩個類在html標記之前定義(例如:'.class1 .class2 html'轉換爲'.class1 html .class2' –

+0

我將此場景的正則表達式添加到答案。對不起,在我的手機上打字很慢。 –