我希望能够根据红宝石所属的组来修改匹配项。如下所示:
def splitter(m)
if match == 1
return m+"\n"
elsif match == 2
return m+"\t"
elsif match == 3
return "\n"+m
end
s = "0 1 2 3"
s.gsub(/(1)|(2)|(3)/) {|m| splitter(m)}
s应该导致
"0 1\n 2\t \n3"
答案 0 :(得分:1)
您需要使用\d
而不是(1)(2)(3)
,并且匹配的单词是一个字符串,因此您需要与字符串进行比较,而与数字进行比较
def splitter(match)
if match == "1"
return match+"\n";
elsif match == "2"
return match+"\t";
elsif match == "3"
return "\n"+match;
else return match;
end;
end;
s = "0 1 2 3";
l = s.gsub(/\d/) {|m| splitter(m)};
print l;
答案 1 :(得分:0)
我敢肯定,有很多更简单的方法可以完成您想做的事情,但是可以考虑一下:
re = /(1)|(2)|(3)/
str = '0 1 2 3'
str.scan(re) do |match|
puts match.to_s
match.each { |x| puts x}
if match.include?('1')
puts 'return 1'
end
if match.include?('2')
puts 'return 1'
end
if match.include?('3')
puts 'return 3'
end
end
["1", nil, nil]
1
return 1
[nil, "2", nil]
2
return 1
[nil, nil, "3"]
3
return 3