在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中创建这些单行?
解决方法
string = "the quick brown fox jumps over the lazy dog." extract_string = string[/fox (.*?) dog/,1] # => "jumps over the lazy" extract_array = string.scan(/the (.*?) fox .*?the (.*?) dog/).first # => ["quick brown","lazy"]
extract_string = string[/MISSING_CAT (.*?) dog/,1] # => nil extract_array = string.scan(/the (.*?) MISSING_CAT .*?the (.*?) dog/).first # => nil