1

在我的 Perl 脚本中,我有一个包含特定文件路径的变量。我需要创建一个正则表达式,可以从该变量中捕获特定的 8 位字符串。

$file_path = "/home/attachments/00883227/sample.txt 我想在“附件”之后立即捕获数字字符串时。

我的(不成功的)尝试:

if($file_path =~ /attachments\/(\d{1,2,3,4,5,6,7,8}+)/)
    { $number = $1; }

但是,当我运行此脚本时,$number 变量中似乎没有存储任何内容。解决这个问题可能很简单?请原谅我的无知,我对 Perl 很陌生。

4

8 回答 8

5

You don't need to give so much of numbers in the braces. Simply use {8} to enforce matching of 8 digits. And since you have / inside your string, you can use a different delimiter, instead of escaping the slashes:

if($file_path =~ m!attachments/(\d{8})!)
   { $number = $1; }
于 2013-07-05T18:59:09.377 回答
5

Close, just use (\d{8}), like:

$file_path =~ /attachments\/(\d{8})\b/

Also added \b so that it doesn't capture any longer numbers.

于 2013-07-05T18:59:23.677 回答
3

If you want to match exactly 8 digits, just use \d{8}:

if($file_path =~ /attachments\/(\d{8})/)
    { $number = $1; }
于 2013-07-05T18:58:58.920 回答
3
my ($number) = ( $file_path =~ m{ (attachments/( [0-9]{8} ) }x );

Using pattern delimiters other than / such as m{ }, you avoid the so-called leaning toothpick syndrome caused by the need to escape and / characters that appear in the pattern.

By assigning to $number in list context, the captured substring goes into $number immediately.

By using the x option, you make your pattern somewhat more readable.

于 2013-07-05T18:59:13.423 回答
1
my ($number) = $file_path =~ m{attachments/(\d+)};

如果你想确保它的长度正好是八位数,

my ($number) = $file_path =~ m{attachments/(\d{8})(?!\d)};
于 2013-07-05T19:16:59.503 回答
1

Try using:

if($file_path =~ /attachments\/(\d+)/)
{ $number = $1; }

{ , } is used to limit the number of times a certain character (or group of characters) to repeat. {n,m} means that the character (or group) should repeat at least n times and at most m times.

If you're certain the string of digits is 8-digits long, you then use:

if($file_path =~ /attachments\/(\d{8})/)
{ $number = $1; }

{ } (without commas) will match exactly the number specified.

于 2013-07-05T18:58:59.847 回答
1

简单地给出限制。

例如, \d{3,8} 它将返回 3-8 长度之间的数字。

于 2021-10-14T09:59:33.303 回答
0

是正好是 8 位数字还是介于 1 到 8 位数字之间?

由于您将/attachments/其视为字符串的一部分,因此您可能不想使用标准/../分隔符。也许切换到m{..}or m#..#

if ( $file_path =~ m#/attachments/\(d{1,8})/# ) {

这将捕获 1 到 8 位数字。要准确捕获 8 个:

my $number;
if ( $file_path =~ m#/attachments/(\d{8})/# ) {
   $number = $1;
   ...
}
else {
    ....
}

请注意,我在声明$digit_string之前定义。if这样,它在if语句之后的范围内(并且在if语句内部。(您正在使用use strict;?对吗?)

于 2013-07-05T19:16:23.450 回答