Ruby one-liner用于捕获正则表达式匹配

前端之家收集整理的这篇文章主要介绍了Ruby one-liner用于捕获正则表达式匹配前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
在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"]

如果未找到匹配项,此方法也将返回nil(而不是抛出错误).

extract_string = string[/MISSING_CAT (.*?) dog/,1]
# => nil

extract_array = string.scan(/the (.*?) MISSING_CAT .*?the (.*?) dog/).first
# => nil

猜你在找的Ruby相关文章