0

我的脚本中有一个函数,它应该接收一个 HTML 字符串并返回相同的字符串,但所有元素都应更改为高 2 级的元素(即 h1->h3、h2-> h4 等)。这个原因需要独立于大小写,并且它不能删除属性,但是,我也不打算使用完整的 html 解析器,因为这是一个相当简单的任务,所以我想我会去这与正则表达式。问题是(我对 vbscript 相当陌生)我不知道如何达到预期的效果。

我目前拥有的是这样的:

Function fiksoverskrifter(html)
   Dim regex, matches, match
   Set regex = New RegExp
   regex.Pattern = "<(/?)h([0-9])(.*?)>"
   regex.IgnoreCase = True
   regex.Multiline = False

   fiksoverskrifter = html

   Set matches = regex.Execute(html)
   For Each match in matches

   Next

   Set regex = Nothing
   Set matches = Nothing
   Set match = Nothing
End Function

我在For Each-loop 中想要的只是交换数字,但是,我不知道该怎么做(我什至不确定match-object 暴露了哪些属性,而且我一直无法在网上找到它) .

我应该如何完成这个功能?

4

2 回答 2

2

如果只是替换标题的情况,我会使用replace()

For i = 4 To 1 Step -1
    strHtml = replace(strHtml, "<h" & cstr(i), "<h" & cstr(i + 2), 1, -1, vbTextCompare)
    strHtml = replace(strHtml , "</h" & cstr(i), "</h" & cstr(i + 2), 1, -1, vbTextCompare)
Next

(HTML 规范仅对H1- H6- 不确定是否要忽略H5&有效H6

如果你想坚持使用正则表达式选项,我建议使用regex.replace()

我知道在 JavaScript 中你可以将匹配的模式传递给一个函数并使用该函数作为替换,这正是你在这里需要的 - 但我从未见过在 VBSCRIPT 中这样做过,例如: 使用 RegExp 匹配括号内的数字然后递增它

编辑1:

找到对匹配集合和匹配对象的引用:

http://msdn.microsoft.com/en-us/library/ms974570.aspx#scripting05_topic3

因此,您可以从 match.value 属性中读取匹配项,但我认为您仍然需要求助于第二次替换

于 2012-06-12T09:50:35.267 回答
0

这是一个更通用的解决方案,但可能偏离主题,因为它是在 Perl 中,而不是在 VBScript 中。请注意,我记录了它以对抗正则表达式往往具有的只写效果。

C:\TEMP :: more /t4 hdradj.pl
use strict;
use warnings;

# Make a subroutine that will adjust HTML headers
# (like h1, H2) by doing string replacement.
# Will only work properly for the range from 1 to 9.
sub mk_header_adjuster {
    my( $adjustment, $lower, $upper ) = @_;
# Compile substitution expression to adjust headers like h1, H2.
# Left-hand side matches headers from the range specified.
# Uses word boundaries (\b) and a character range (square brackets).
# Captures matches for "h|H" in $1 and for the level in $2.
# Right-hand side uses an eval (e-switch) to compute substitution.
# Case is ignored (i-switch), replacement is global (g-switch).
# Wraps expression in subroutine to modify first argument.
    my $str = <<"EOSUB";
sub {
    \$_[0] =~ s/\\b(h)([$lower-$upper])\\b/\$1 . (\$2 + $adjustment)/ige
}
EOSUB
#   print $str, "\n"; # debug output
    my $sub = eval $str; # compile expression
    die $@ if $@; # abort in case of errors in eval compilation
    return $sub;
}

# ==== main ====
# Test the above subroutine is working properly.
my $test_input = <<'EOS';
<h1>eins</h1>
<p>...
<h2 bla="blub">eins blub</h2>
< H2 >zwei </ H2>
<h3 >drei </h3>
<h4>vier </h4>
<h5>fünf </h5>
EOS

# Compile a header adjuster moving headers 2 to 4 by 2 levels down.
my $adjuster = mk_header_adjuster 2, 2, 4;
my $number_of_replacements = $adjuster->( $test_input );
printf STDERR
"Replaced %u header tags in supplied input.\n", $number_of_replacements;
print $test_input;
于 2012-06-12T10:34:26.380 回答