从另一个字符串中提取所需的子字符串 -Perl [英] Extract the required substring from another string -Perl

查看:17
本文介绍了从另一个字符串中提取所需的子字符串 -Perl的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从 Perl 的一行中提取一个子字符串.我举个例子解释一下:

I want to extract a substring from a line in Perl. Let me explain giving an example:

fhjgfghjk3456mm   735373653736
icasd 666666666666
111111111111

在上面几行中,我只想提取 12 位数字.我尝试使用 split 函数:

In the above lines, I only want to extract the 12 digit number. I tried using split function:

my @cc = split(/[0-9]{12}/,$line);
print @cc;

但它所做的是删除字符串的匹配部分并将剩余部分存储在 @cc 中.我想要打印与图案匹配的部分.我该怎么办?

But what it does is removes the matched part of the string and stores the residue in @cc. I want the part matching the pattern to be printed. How do I that?

推荐答案

$1 内置变量存储来自正则表达式的最后一个匹配项.此外,如果您对整个字符串执行正则表达式,它将返回整个字符串.这里最好的解决方案是在匹配项周围加上括号,然后打印 $1.

The $1 built-in variable stores the last match from a regex. Also, if you perform a regex on a whole string, it will return the whole string. The best solution here is to put parentheses around your match then print $1.

my $strn = "fhjgfghjk3456mm 735373653736
icasd
666666666666 111111111111";
$strn =~ m/([0-9]{12})/;
print $1;

这使得我们的正则表达式只匹配十二位数字,然后我们用 $1 返回匹配.

This makes our regex match JUST the twelve digit number and then we return that match with $1.

这篇关于从另一个字符串中提取所需的子字符串 -Perl的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆