使用Perl Regex进行剥离/替换

时间:2009-06-05 21:55:20

标签: regex perl strip

所以我对编程很新,所以这可能是一个愚蠢的问题,但我特意尝试使用正则表达式去除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 个答案:

答案 0 :(得分: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
}

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

答案 1 :(得分:3)

如果您知道$strip中有颜色属性,则可以使用

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

注意事项:

  • i修饰符不区分大小写匹配
  • s修饰符表示'。'字符匹配任何字符包括换行符

答案 2 :(得分: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你不想要的行。

答案 3 :(得分:0)

不确定为什么没有提到这一点,但是花括号在正则表达式中具有特殊含义,因此需要进行转义。