Ruby global match regexp?

RubyRegex

Ruby Problem Overview


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?

Ruby Solutions


Solution 1 - Ruby

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.

Solution 2 - Ruby

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

Solution 3 - Ruby

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionnever_had_a_nameView Question on Stackoverflow
Solution 1 - RubyAboutRubyView Answer on Stackoverflow
Solution 2 - RubyivanreeseView Answer on Stackoverflow
Solution 3 - RubywuputahView Answer on Stackoverflow