【发布时间】:2013-07-09 05:34:00
【问题描述】:
我试图在一行的两个点之间获取文本,但我的程序返回整行。
例如:我有如下文字:
我的示例数据 1,2 for perl .version 1_1。
我使用了以下匹配语句
$x =~ m/(\.)(.*)(\.)/;
我的 $x 输出应该是版本 1_1,但我将整行作为我的匹配项。
【问题讨论】:
-
$x 不是您的匹配项,而是您的正则表达式的输入。
我试图在一行的两个点之间获取文本,但我的程序返回整行。
例如:我有如下文字:
我的示例数据 1,2 for perl .version 1_1。
我使用了以下匹配语句
$x =~ m/(\.)(.*)(\.)/;
我的 $x 输出应该是版本 1_1,但我将整行作为我的匹配项。
【问题讨论】:
在您的代码中,$x 的值在匹配后不会改变。
当 $x 与 m/(.)(.*)(.)/ 成功匹配时,您的三个捕获组将包含 '.'、'version 1_1' 和 '.'分别(按给定的顺序)。 $2 将为您提供“版本 1_1”。
考虑到您可能只需要“版本 1_1”部分,您无需捕获这两个点。这段代码会给你同样的结果:
$x =~ m/\.(.*)\./;
print $1;
【讨论】:
这样做应该足够简单:
#!/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";
}
$ ./test.pl
got: get some stuff
got: capture this
got: some data you want
【讨论】:
试试这个:
my $str = "My sampledata 1,2 for perl .version 1_1.";
$str =~ /\.\K[^.]+(?=\.)/;
print $&;
句点必须从字符类中转义。
\K 重置之前匹配的所有内容(您可以将其替换为lookbehind (?<=\.))
[^.] 表示除句点之外的任何字符。
对于几个结果,您可以这样做:
my $str = "qwerty .target 1.target 2.target 3.";
my @matches = ($str =~ /\.\K[^.]+(?=\.)/g);
print join("\n", @matches);
如果您不想使用两次,可以这样做:
my $str = "qwerty .target 1.target 2.target 3.";
my @matches = ($str =~ /\.([^.]+)\./g);
print join("\n", @matches)."\n";
【讨论】: