0

我想从字符串中提取大小值。可以通过以下两种方式之一来格式化字符串:

数据大小:(2000 字节)

或者

文件数据大小:(2082 字节)

如果字符串存在于文件中,它只会出现一次。

到目前为止,我有:

#!/usr/bin/perl

use strict;
use warnings;

open FILE, "</tmp/test";
my $input = do { local $/; <FILE> };

my ($length) = $input =~ /(file)?\s*Data-Size: \((\d+) bytes\)/m;                   

$length or die "could not get data length\n";
print "length: $length\n";

问题似乎在于将 word 文件设为可选。我想我可以这样做:

(文件)?

但是,当 word 文件不存在时,这似乎会停止匹配。此外,当单词文件存在时,它会将 $length 设置为字符串“file”。我认为这是因为文件周围的括号也意味着提取。

那么如何匹配两个字符串中的任何一个并提取大小值呢?

4

2 回答 2

4

您想要在$length. 为此,您可以使用

my (undef, $length) = $input =~ /(file)?\s*Data-Size: \((\d+) bytes\)/;

或者

my $length = ( $input =~ /(file)?\s*Data-Size: \((\d+) bytes\)/ )[1];

But a much better approach would be to avoid capturing something you're not interested in capturing.

my ($length) = $input =~ /(?:file)?\s*Data-Size: \((\d+) bytes\)/;

Of course, you'd get the same result from

my ($length) = $input =~ /Data-Size: \((\d+) bytes\)/;

By the way, I removed the needless /m. /m changes the meaning of ^ and $, yet neither are present in the pattern.

于 2012-12-08T06:47:24.100 回答
0

Just my 2 cents, you can make optional matching other way:

/(file|)\s*Data-Size: ((\d+) bytes)/

于 2012-12-09T04:42:44.423 回答