代码之家  ›  专栏  ›  技术社区  ›  Rubioli

从字符串中提取子字符串并输出一些行

  •  -1
  • Rubioli  · 技术社区  · 6 年前

    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
    
    2 回复  |  直到 6 年前
        1
  •  2
  •   Cary Swoveland    6 年前

    @斯皮克曼使用了 使 .*

    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 "
    

    丢弃返回值。

        2
  •  2
  •   spickermann    6 年前

    我会用 String#scan

    string = "hello glass car [clock][flower] candy [apple]"
    string.scan(/(?<=\[).*?(?=\])/).each { |word| puts "#{word} have" }