在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中创建这些单行?
使用String#match
和MatchData#[]
或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)
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)
归档时间: |
|
查看次数: |
2188 次 |
最近记录: |