我该如何在Perl中提取符号后的字符串?
我尝试过一些搜索,但即使我找到的代码也不能正常工作。
我正在尝试提取冒号后面的字符串。因此,我想显示冒号后的所有内容。
例如:
string = day1: string over here
substring = string over here
到目前为止,我尝试过:
$substring = $string=~ /(\:.*)\s*$/;
但它只会一遍又一遍地输出数字 1。
这是因为在标量上下文中,模式匹配是布尔测试。如果你想捕获括号内容(捕获组),你需要一个列表上下文。即使列表只有一个元素也可以:
尝试这个:
my ( $substring ) = $string=~ /(\:.*)\s*$/;
差异可能有点微妙,但基本上 - 我们将来自模式匹配的“所有命中”分配给一个列表...该列表包含一个元素。
请注意 - 这样您就可以执行以下操作:
my @matches = $string =~ m/(.)/g;
您可能会收到多个“匹配项”。如果按照上述操作,您将只得到第一个匹配项——这与您的模式无关,但您可以执行以下操作:
And get multiple 'hits' returned. If you do as above, you will only get the first match - which is irrelevant given your pattern, but you can do:
my ( $key, $value ) = $string =~ m/(\w+)=(\w+)/;
例如。
我通常使用括号从文本中提取一部分,然后引用存储在$1变量中的结果。
看下面的例子:
my $text = "day1: string over here";
print $1 if ($text =~ /:\s*(.+)$/);
my $text = "day1: string over here";
my ($a) = $text =~ /:\s*(.+)$/;
print $a;
您也可以使用分割函数来实现对所需子字符串的提取:
#!/usr/bin/perl
use warnings;
use strict;
my $string = "day1: string over here";
my (undef, $substring) = split(':\s*', $string);
print $substring, "\n";
输出:
string over here
或者你可以使用正则表达式中的捕获组()
来获取这个:
my $string = "day1: string over here";
$string =~ m/(.*)\:\s+(.*)$/;
my $substring = $2;
print $substring, "\n";
(.*)
,直接访问 $1
。或者我有什么遗漏吗? - Sobrique
/:\s*(.*)\s*$/
。 - hjpotter92