Ruby global match regexp?

后端 未结 3 1252
终归单人心
终归单人心 2020-12-08 03:42

In other languages, in RegExp you can use /.../g for a global match.

However, in Ruby:

\"hello hello\".match /(hello)/

相关标签:
3条回答
  • 2020-12-08 04:23

    Here's a tip for anyone looking for a way to replace all regex matches with something else.

    Rather than the //g flag and one substitution method like many other languages, Ruby uses two different methods instead.

    # .sub — Replace the first
    "ABABA".sub(/B/, '') # AABA
    
    # .gsub — Replace all
    "ABABA".gsub(/B/, '') # AAA
    
    0 讨论(0)
  • 2020-12-08 04:42

    use String#scan. It will return an array of each match, or you can pass a block and it will be called with each match.

    All the details at http://ruby-doc.org/core/classes/String.html#M000812

    0 讨论(0)
  • 2020-12-08 04:43

    You can use the scan method. The scan method will either give you an array of all the matches or, if you pass it a block, pass each match to the block.

    "hello1 hello2".scan(/(hello\d+)/)   # => [["hello1"], ["hello2"]]
    
    "hello1 hello2".scan(/(hello\d+)/).each do|m|
      puts m
    end
    

    I've written about this method, you can read about it here near the end of the article.

    0 讨论(0)
提交回复
热议问题