一次对整个文件进行操作,您可以使用:
s/(\ba(?=(?:\.|,|\s|{|#)))([^}{]*?{[^}]*?text-decoration:\s*)none(\s?!important)?;/$1$2underline;/g
格式更好,这是:
s/ # find and replace
( # group 1
\b # a word boundary
a # followed by 'a'
(?= # where the next character (positive lookahead)
(?: # (inside a non-capturing group)
\.|,|\s|{|# # is one of '.', ',', '{', '#' or whitespace
)
)
)
( # group 2
[^}{]*? # then non-greedily match anything up to a '{' or '}'
# if '}' is found, the next character will not match
# and therefore the whole regex will not match
{ # and find the '{'
[^}]*? # and then non-greedily match anything until we
# find 'text-decoration', but don't keep matching
# when a '}' is found
text-decoration: # then find 'text-decoration'
\s* # and optional whitespace
)
none # and 'none'
(\s?!important)? # and optional '!important'
; # and a ';'
/
$1 # replace by group 1
$2 # then group 2
underline; # then 'underline;'
/g
示例文件:
$ cat test.css
a { text-decoration: none; }
b, a { text-decoration: none; }
b, a, u { text-decoration: none; }
b, a.cat, u { text-decoration: none; }
b, a.cat, u { text-decoration: none !important; }
b, a, u {
text-decoration: none;
}
b, a, u {
color: red;
text-decoration: none;
}
b, a, u {
color: red;
text-decoration: none;
padding: 10px;
}
结果:
perl -0777 -p -e 's/(\ba(?=(?:\.|,|\s|{|#)))([^}{]*?{[^}]*?text-decoration:\s*)none(\s?!important)?;/$1$2underline;/g' test.css
a { text-decoration: underline; }
b, a { text-decoration: underline; }
b, a, u { text-decoration: underline; }
b, a.cat, u { text-decoration: underline; }
b, a.cat, u { text-decoration: underline; }
b, a, u {
text-decoration: underline;
}
b, a, u {
color: red;
text-decoration: underline;
}
b, a, u {
color: red;
text-decoration: underline;
padding: 10px;
}
您可以使用 perl 的-i
标志(不要忘记设置备份扩展名!)对文件进行就地操作。
显然还有很多其他可能的 CSS 规则可以包括a
; 例如html>a
或div a b
;这个正则表达式不会找到第一个,会找到第二个,但在这两种情况下都是“错误的”。基本上,只有当您可以对您正在操作的文本做出强有力的假设时,您才能将正则表达式用于这些类型的任务。
更新添加}
到规则的一部分以避免匹配,例如:
b { background-image: url('http://domain.com/this is a picture.jpg'); }
u { text-decoration: none; }