0

所以我对一般编程很陌生,所以这可能是一个愚蠢的问题,但我特别想使用正则表达式来去除 CSS 标记。基本上我有这个:

.style1 {  
    font-size: 24px;  
    font-weight: bold;  
    color: #FFEFA1;  
} 

我希望它看起来像这样:

.style1:color:#FFEFA1

我想保留样式名称、颜色属性和颜色十六进制,中间有一个冒号,没有空格。我正在尝试类似以下的事情来实现这一点:

$strip =~ s/\w+\}|\w+^#([0-9a-fA-F]{3})|([0-9a-fA-F]{6})//;

但它不起作用。有人愿意让我走上正确的道路吗?

干杯。

4

4 回答 4

4

与大多数 perl 答案一样,这以“使用 CPAN”开头。你曾经想做的一切都已经完成了。

use CSS;

my $css = CSS->new();

$css->read_string('
.style1 {
font-size: 24px;
font-weight: bold;
color: #FFEFA1;
} 
');

$color = $css->get_style_by_selector('.style1')
             ->get_property_by_name('color')
             ->values;

使用 CPAN 中的 CSS 等模块意味着有人已经考虑了您的正则表达式解决方案没有考虑到的边缘情况。考虑:

.someClass, div.otherClass, #someid {
    color: #aa00aa
}

使用正则表达式为特定选择器获取颜色变得更加困难。

于 2009-06-06T14:03:25.167 回答
3

如果你知道里面会有一个颜色属性,$strip你可以使用

$strip =~ s!\s*{.*color:\s*(#[0-9a-f]{6});.*}!:color:$1!is;

注意事项:

  • i修饰符不区分大小写匹配
  • s修饰符表示'.' 字符匹配任何字符,包括换行符
于 2009-06-05T22:32:02.007 回答
0

我在 plan9port 环境 shell 中编写了这个,但它很容易移植到任何 linux。

这段代码创建了一个 sed 脚本来旋转您的数据。

#!/usr/local/plan9/bin/rc
# .style1:color:#FFEFA1
cat > this.sed <<EOF
# for lines which start with .
/\./{
# strip open curly brace
s, {,:,
# store element tag
h
# skip to next line
n
}

# strip close curly brace
/}/d

# for other lines
{
# remove spaces
s, ,,g
# get rid of ; at end
s,;$,,g
# pull back in the element tag
G
# join to one line
s,\n,,
# shift element tag to the start
# sed in plan 9 is a little different
# for gnu sed, use \( \) and \+
s,(.*)(\.[^.]+$),\2\1,
# finally print something
p
}
EOF

这段代码针对 sed 脚本运行您的输入,

cat | sed -n -f this.sed <<EOF
.style1 {
font-size: 24px;
font-weight: bold;
color: #FFEFA1;
}
EOF

生成此输出。

.style1:font-size:24px
.style1:font-weight:bold
.style1:color:#FFEFA1

您可以 grep 查找您想要的行,或者“grep -v”您不想要的行。

于 2009-06-05T22:49:22.220 回答
0

不知道为什么没有提到这一点,但大括号在正则表达式中具有特殊含义,因此需要转义。

于 2009-06-06T21:03:37.263 回答