2016-07-06 47 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

我将此场景的正则表达式添加到答案。对不起,在我的手机上打字很慢。 –