在Perl中,我使用以下的一行语句通过正则表达式从字符串中提取匹配项并将其赋值。这个语句查找单个匹配项并将其赋值给一个字符串:
my $string = "the quick brown fox jumps over the lazy dog.";
my $extractString = ($string =~ m{fox (.*?) dog})[0];
结果:$extractString == '跳过那只懒狗'
以下代码可以从多个匹配项中创建一个数组:
my $string = "the quick brown fox jumps over the lazy dog.";
my @extractArray = $string =~ m{the (.*?) fox .*?the (.*?) dog};
结果: @extractArray == ['quick brown', 'lazy']
在Ruby中是否有相应的方法可以创建这些单行代码?
s.match(/fox (.*?) dog/)[1]
方法的问题。如果没有找到匹配项,Ruby 2.1会抛出“undefined method '[]'”错误。例如,将其更改为s.match(/fox (.*?) cat/)[1]
就会出错。 - Alan W. Smith(s.match(/fox (.*?) cat/) || [])[1]
- falsetru