remove specific rules out of inline CSS
i'd like to remove some specific css rules (i.e. width and height) out of inline style attributes.
so i want to transform the 开发者_如何学Cfollowing:
<table id="foo" style="border:1px #000 solid; width: 100px; height: 100px;">
into
<table id="foo" style="border:1px #000 solid">
is there a handy regex that solves my problem?
thank you all in advance
Maybe try this (tested in Vim and Ruby):
/(width|height):\s*\d+(px|%);?//
Of course you should use your editor's (or language's) syntax for regexps (for example in Vim you have to prepend backslash before '(','|',')' and '+'
Enable regex search in your editor and try:
width="[^"]*"
height="[^"]*"
Your question is not very specific, but how about /[\s;"']width: .+;/
. You need to feed that to a replace function or something, but I can't help you there because I don't know what language you're in.
Beware: regular expressions cannot correctly parse HTML.
Use a parser instead.
#! /usr/bin/perl
use warnings;
use strict;
use HTML::Parser;
die "Usage: $0 html-file\n" unless @ARGV == 1;
sub start {
my($tag,$attr,$attrseq,$text,$skipped) = @_;
print $skipped;
unless ($attr->{style} && $attr->{style} =~ /width|height/) {
print $text;
return;
}
my %style = $attr->{style} =~ /
\s* # optional leading space
(.+?) : # property, e.g., width
\s* # optional separating space
([^;]+) # value, e.g., 100px
;? # optional separator
/gx;
delete @style{qw/ width height /};
$attr->{style} = join "; " =>
map "$_: $style{$_}",
keys %style;
print "<$tag ",
join(" " => map qq[$_="$attr->{$_}"], @$attrseq),
">";
}
my $p = HTML::Parser->new(
api_version => 3,
marked_sections => 1,
start_h => [ \&start => "tag, attr, attrseq, text, skipped_text" ],
end_h => [ sub { print @_ } => "skipped_text, text" ],
);
undef $/;
$p->parse(<>);
No, you generally cannot do all that in a regular expression, because HTML is not a regular language.
Use an HTML parser to get at the style
attribute from table
tags, then use the regular expressions width:.+?(;|$)
and height:.+?(;|$)
.
精彩评论