2013-07-11 103 views
1

我是perl的新手。我試圖在一行的兩個點之間得到一個文本,但是我的程序返回了整行。perl中匹配

例如:我有一個看起來像 的文本,我的樣本數據1,2爲perl.version 1_1。

我用下面的匹配語句

$x =~ m/(\.)(.*)(\.)/; 

我輸出$ X版本應爲1_1,但我得到了整條生產線爲我的比賽。

我將不勝感激任何幫助。 謝謝。

+0

$ x ist不是你的匹配,它是你的正則表達式的輸入。 – innaM

回答

0

試試這個:

my $str = "My sampledata 1,2 for perl .version 1_1."; 
$str =~ /\.\K[^.]+(?=\.)/; 
print $&; 

週期必須逃出字符類。

\K重置所有以前已經被匹配

[^.]意味着除了一段任意字符(您可以通過回顧後(?<=\.)更換)。

幾年的結果,你可以這樣做:

my $str = "qwerty .target 1.target 2.target 3."; 
my @matches = ($str =~ /\.\K[^.]+(?=\.)/g); 
print join("\n", @matches); 

如果你不想使用2-3次期間,你可以這樣做:

my $str = "qwerty .target 1.target 2.target 3."; 
my @matches = ($str =~ /\.([^.]+)\./g); 
print join("\n", @matches)."\n"; 
0

應該足夠簡單,做一些事情像這樣:

#!/usr/bin/perl 

use warnings; 
use strict; 

my @tests = (
    "test one. get some stuff. extra", 
    "stuff with only one dot.", 
    "another test line.capture this. whatever", 
    "last test . some data you want.", 
    "stuff with only no dots", 
); 

for my $test (@tests) { 
    # for this example, I skip $test if the match fails, 
    # otherwise, I move on do stuff with $want 
    next if $test !~ /\.(.*)\./; 
    my $want = $1; 
    print "got: $want\n"; 
} 

OUTPUT:

$ ./test.pl 
got: get some stuff 
got: capture this 
got: some data you want 
3

在您的代碼中,匹配後$ x的值不會更改。

當$ x與m /(.)(.*)(.)/匹配成功時,您的3個捕獲組將包含'。','version 1_1'和'。'。 (按給定的順序)。 $ 2會給你'版本1_1'。

考慮到您可能需要的只是「版本1_1」部分,您無需捕獲2個點。這段代碼會給你相同的結果:

$x =~ m/\.(.*)\./; 
print $1;