从另一个字符串-Perl中提取所需的子字符串 [英] Extract the required substring from another string -Perl
问题描述
我想从Perl中的一行中提取一个子字符串。让我来解释一个例子:
fhjgfghjk3456mm 735373653736
icasd 666666666666
111111111111
code>
在上面的几行中,我只想提取12位数字。我尝试使用 split
函数:
my @cc = split(/ [0-9] {12} /,$线);
打印@cc;
但它所做的是删除字符串的匹配部分,并将残差存储在 @cc
。我想要打印与图案匹配的部分。我怎么做?
$ 1内置变量存储来自正则表达式的最后一个匹配。另外,如果你对整个字符串执行一个正则表达式,它将返回整个字符串。这里最好的解决办法是在你的比赛中放上括号,然后打印1美元。
my $ strn =fhjgfghjk3456mm 735373653736\\\
icasd\\ \\ n666666666666 111111111111;
$ strn =〜m /([0-9] {12})/;
打印$ 1;
这使得我们的正则表达式只匹配十二位数字,然后我们用$ 1返回匹配。 p>
I want to extract a substring from a line in Perl. Let me explain giving an example:
fhjgfghjk3456mm 735373653736
icasd 666666666666
111111111111
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;
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?
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\nicasd\n666666666666 111111111111";
$strn =~ m/([0-9]{12})/;
print $1;
This makes our regex match JUST the twelve digit number and then we return that match with $1.
这篇关于从另一个字符串-Perl中提取所需的子字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!