2012-07-02 123 views
3

我想從Perl中的一行中提取子字符串。讓我解釋一個例子:從另一個字符串中提取所需的子字符串-Perl

fhjgfghjk3456mm 735373653736 
icasd 666666666666 
111111111111 

在上面的行中,我只想提取12位數字。我嘗試使用split功能:

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

但它的作用是去除字符串匹配的部分,並存儲在@cc殘渣。我想要打印與圖案匹配的部分。我怎麼樣?

回答

3

的$ 1個內置變量存儲從最後一個正則表達式匹配。另外,如果你對整個字符串執行一個正則表達式,它將返回整個字符串。這裏最好的解決方案是在你的比賽周圍放上括號,然後打印1美元。

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

這使得我們的正則表達式匹配只是十二位數字,然後我們返回與$ 1的匹配。

+0

感謝..這是非常簡單的。但請相信我,我發佈這個問題之前,讀了很多。非常感謝.. – Amey

+7

如果沒有條件,你不應該使用'$ 1'。 – TLP

3
#!/bin/perl 
my $var = 'fhjgfghjk3456mm 735373653736 icasd 666666666666 111111111111'; 
if($var =~ m/(\d{12})/) { 
    print "Twelve digits: $1."; 
} 
+0

... Rawkode上解決了我的問題.. – Amey

7

你可以用regular expressions做到這一點:

#!/usr/bin/perl 
my $string = 'fhjgfghjk3456mm 735373653736 icasd 666666666666 111111111111'; 
while ($string =~ m/\b(\d{12})\b/g) { 
    say $1; 
} 

測試這裏的正則表達式:http://rubular.com/r/Puupx0zR9w

use YAPE::Regex::Explain; 
print YAPE::Regex::Explain->new(qr/\b(\d+)\b/)->explain(); 

The regular expression: 

(?-imsx:\b(\d+)\b) 

matches as follows: 

NODE      EXPLANATION 
---------------------------------------------------------------------- 
(?-imsx:     group, but do not capture (case-sensitive) 
         (with^and $ matching normally) (with . not 
         matching \n) (matching whitespace and # 
         normally): 
---------------------------------------------------------------------- 
    \b      the boundary between a word char (\w) and 
          something that is not a word char 
---------------------------------------------------------------------- 
    (      group and capture to \1: 
---------------------------------------------------------------------- 
    \d+      digits (0-9) (1 or more times (matching 
          the most amount possible)) 
---------------------------------------------------------------------- 
)      end of \1 
---------------------------------------------------------------------- 
    \b      the boundary between a word char (\w) and 
          something that is not a word char 
---------------------------------------------------------------------- 
)      end of grouping 
---------------------------------------------------------------------- 
1
#!/usr/bin/env perl 

undef $/; 
$text = <DATA>; 
@res = $text =~ /\b\d{12}\b/g; 
print "@res\n"; 

__DATA__ 
fhjgfghjk3456mm 735373653736 
icasd 666666666666 
111111111111 
感謝
相關問題