我有这个字符串:
a = "hello glass car [clock][flower] candy [apple]"
我该如何在[word]
之类的方括号中排列单词,并为其中的每个项目输出如下?
array = ['clock', 'flower', 'apple']
array.each do |a|
puts a + 'have'
end
# >> clock have
# >> flower have
# >> apple have
答案 0 :(得分:2)
我将String#scan
与正则表达式配合使用,该正则表达式匹配方括号中的所有内容:
string = "hello glass car [clock][flower] candy [apple]"
string.scan(/(?<=\[).*?(?=\])/).each { |word| puts "#{word} have" }
答案 1 :(得分:2)
@spickermann使用正向查找和正向查找,并通过添加问号使.*
非贪婪。那是我的偏爱,但是我会提到另一种正常的方法,即使用捕获组,然后再使用一种不产生中间数组的方法。
string = "hello glass car [clock][flower] candy [apple]"
为
string.scan(/\[(.*?)\]/)
#=> [["clock"], ["flower"], ["apple"]]
我们会写
string.scan(/\[(.*?)\]/).flatten.each { |word| puts "#{word} have" }
clock have
flower have
apple have
或
string.scan(/\[(.*?)\]/).each { |(word)| puts "#{word} have" }
clock have
flower have
apple have
请注意,如果将non-greedy
限定词从正则表达式中删除,我们将获得以下信息:
arr = string.scan(/\[(.*)\]/)
#=> [["clock][flower] candy [apple"]]
即包含单个元素的数组,这是包含单个元素字符串的数组
"clock][flower] candy [apple"
请参见String#scan,尤其是对(捕获)组的引用。
如果按照问题所建议的那样,您只想打印结果而不需要数组["clock", "flower", "apple"]
,则可以编写以下内容:
string.gsub(/(?<=\[).*?(?=\])/) { |word| puts "#{word} have" }
clock have
flower have
apple have
#=> "hello glass car [][] candy []"
或
string.gsub(/\[(.*?)\]/) { puts "#{$1} have" }
clock have
flower have
apple have
#=> "hello glass car candy "
丢弃返回值。