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

Ala*_*ith 7 ruby regex

在Perl中,我使用以下一行语句通过正则表达式从字符串中提取匹配项并分配它们.这个找到一个匹配并将其分配给一个字符串:

my $string = "the quick brown fox jumps over the lazy dog.";

my $extractString = ($string =~ m{fox (.*?) dog})[0];
Run Code Online (Sandbox Code Playgroud)

结果: $extractString == 'jumps over the lazy'

这个从多个匹配创建一个数组:

my $string = "the quick brown fox jumps over the lazy dog.";

my @extractArray = $string =~ m{the (.*?) fox .*?the (.*?) dog};
Run Code Online (Sandbox Code Playgroud)

结果: @extractArray == ['quick brown', 'lazy']

是否有相同的方法在Ruby中创建这些单行?

fal*_*tru 8

使用String#matchMatchData#[]MatchData#captures获得匹配的反向引用.

s = "the quick brown fox jumps over the lazy dog."

s.match(/fox (.*?) dog/)[1]
# => "jumps over the lazy"
s.match(/fox (.*?) dog/).captures
# => ["jumps over the lazy"]

s.match(/the (.*?) fox .*?the (.*?) dog/)[1..2]
# => ["quick brown", "lazy"]
s.match(/the (.*?) fox .*?the (.*?) dog/).captures
# => ["quick brown", "lazy"]
Run Code Online (Sandbox Code Playgroud)

UPDATE

为了避免undefined method []错误:

(s.match(/fox (.*?) cat/) || [])[1]
# => nil
(s.match(/the (.*?) fox .*?the (.*?) cat/) || [])[1..2]
# => nil
(s.match(/the (.*?) fox .*?the (.*?) cat/) || [])[1..-1] # instead of .captures
# => nil
Run Code Online (Sandbox Code Playgroud)


saw*_*awa 6

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"]
Run Code Online (Sandbox Code Playgroud)

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

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

extract_array = string.scan(/the (.*?) MISSING_CAT .*?the (.*?) dog/).first
# => nil
Run Code Online (Sandbox Code Playgroud)