Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

However, in Ruby:

"hello hello".match /(hello)/

Only captures one hello.

How do I capture all hellos?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
841 views
Welcome To Ask or Share your Answers For Others

1 Answer

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(/(hellod+)/)   # => [["hello1"], ["hello2"]]

"hello1 hello2".scan(/(hellod+)/).each do|m|
  puts m
end

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...