3

かっこ内のものをimgタグのsrc属性の値に入れようとしています:

while(<TOCFILE>)
{
    $toc_line = $_;
    $toc_line =~ s/<inlineFig.*?(\.\.\/pics\/ch09_inline99_*?\.jpg)*?<\/inlineFig>/<img src="${1}" alt="" \/\>/g;
    $new_toc_file .= $toc_line;
}

したがって、出力に次のようなタグが表示されることを期待していました。

<img src="../pics/ch09_inline99_00" alt="" />

しかし、代わりに私は得ています:

<img src="" alt="" />
4

3 に答える 3

12

正規表現にエラーがあるため、フレーズは何にも一致しません:

inline99_*?\.jpg
        ^^^ 

\d一致させようとしている例のデータから判断すると、星の前で忘れていたと思います。

*?キャプチャされたグループの後に a を置くので、一致することさえ求めていません。だから、それは何も一致しません。それがあなたが得るものです:何もありません。

その上:

($PATTERN)*?

最後に一致したもののみをキャプチャします。それはおそらくあなたが望むものでもありません。例えば:

$_ = 'one two three';
s/(\w+\s*)*/$1/;
print;

「3」を出力します。

于 2008-12-05T17:19:31.950 に答える
3

1) 解析対象の例をいくつか使用できます。

2) 式の最後に「x」を使用する場合、正規表現に空白とコメントを入れて、よりわかりやすくすることができます

3) また、分解すると、( ) 内のものの 2 番目の部分が数字の一致を欠いていることに気付くでしょう... 代わりに、0 以上の '_' を探し、数字を見たときに分割します、したがって一致しません。

while(<TOCFILE>)
{
    $toc_line = $_;
    $toc_line =~ 
      s/                  # replace the follwoing     

         <inlineFig                     # match this text             
         .*?                            # then any characters until the next sequence matches
         (                              # throw the match into $1
            \.\.\/pics\/ch09_inline99_  # ..\pics\cho9_inline99_
            \d*?\.jpg                   # folowed by 0 or more numbers
         )*?                            # keeping doing that until the next sequence matches
         <\/inlineFig>                  # match this text

       /                  # with the follwoing


         <img src="${1}" alt="" \/\>    # some text and the result of $1 above.

       /xg;  # <- the x makes it ignore whitespace and #comments
    $new_toc_file .= $toc_line;
}

4) 前述のとおり、()*? $1 に最後に一致したもののみを返しますが、入力が特定の形式のみである場合、これは問題にはなりません。

于 2008-12-05T17:53:16.107 に答える
1

bartが提案したようにパターンを修正し、ファイルハンドルから読み取ったデータを別の変数に明示的に割り当てる代わりに、「トピック」変数$_の使用を検討してください。

#!/usr/bin/perl

use warnings;
use strict;

my $new_toc_file;

{
    # localizing $_ protects any existing value in the global $_
    # you should localize $_ even if you choose to assign it to a variable

    local $_;

    while(<DATA>) { 
        # in the absence of the bind operator =~, s/// operates against $_
        s!<inlineFig.*?(\.\./pics/ch09_inline99_.*?\.jpg)</inlineFig>!<img src="$1" alt="" />!g;
        $new_toc_file .= $_;
    }
}

print $new_toc_file, "\n";

__END__
<inlineFig>../pics/ch09_inline99_00.jpg</inlineFig>
于 2008-12-05T18:04:41.250 に答える