Reputation: 37690
I have bad css files with rules like this (I can't control the generation of these files):
.class html {
}
.class2 html,.class3 html {
}
html {
}
html .class4 {
}
.class body {
}
.class2 body,.class3 body {
}
body {
}
body .class4 {
}
as you can see, some HTML and BODY rules are put after class name.
What I want to do is to reverse this rules to obtain proper qualifier (tag then class).
My expected result is:
html .class {
}
html .class2 ,html .class3 {
}
html {
}
html .class4 {
}
body .class {
}
body .class2 ,body .class3 {
}
body {
}
body .class4 {
}
I tried using a regex : ([^,]+\s+)(html|body)
with this substitution : $2 $1
, but I don't get what I want. (Repro on regex101)
How to reach my goal ?
PS: this will ends in a custom gulp task, so a js regex solution is required.
Upvotes: 0
Views: 43
Reputation: 626961
You can use
(\.\S+)(\s+)(html|body)
and replace with $3$2$1
.
The regex demo is here.
Expression details:
(\.\S+)
- a literal dot followed with one or more non-whitespaces (Group 1)(\s+)
- one or more whitespaces (Group 2)(html|body)
- either html
or body
literal character sequences (Group 3).The replacement pattern contains the group backreferences that follow in the opposite direction for swapping to occur.
To account for cases like .class .classN html
, use
/(\.\S+(?:\s+\.\S+)*)(\s+)(html|body)/g
where a noncapturing group (?:\s+\.\S+)*
is quantified with *
((zero or more times).
Upvotes: 2