Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby global match regexp?

Tags:

regex

ruby

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?

like image 459
never_had_a_name Avatar asked Aug 28 '10 00:08

never_had_a_name


People also ask

What is global match in regex?

RegExp. prototype. global has the value true if the g flag was used; otherwise, false . The g flag indicates that the regular expression should be tested against all possible matches in a string. Each call to exec() will update its lastIndex property, so that the next call to exec() will start at the next character.

What does =~ mean in Ruby regex?

=~ is Ruby's pattern-matching operator. It matches a regular expression on the left to a string on the right. If a match is found, the index of first match in string is returned. If the string cannot be found, nil will be returned.

What kind of regex does Ruby use?

A regular expression is a sequence of characters that define a search pattern, mainly for use in pattern matching with strings. Ruby regular expressions i.e. Ruby regex for short, helps us to find particular patterns inside a string. Two uses of ruby regex are Validation and Parsing.

How do I match a regex pattern?

To match a character having special meaning in regex, you need to use a escape sequence prefix with a backslash ( \ ). E.g., \. matches "." ; regex \+ matches "+" ; and regex \( matches "(" .


1 Answers

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.

like image 84
AboutRuby Avatar answered Sep 28 '22 03:09

AboutRuby