Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

preg_match_all and preg_replace in Ruby

I am transitioning from php to ruby and I am trying to figure the cognate of the php commands preg_match_all and preg_replace in ruby.

Thank you so much!

like image 804
Spencer Avatar asked Apr 26 '11 14:04

Spencer


People also ask

What is the difference between Preg_match and Preg_match_all?

preg_match stops looking after the first match. preg_match_all , on the other hand, continues to look until it finishes processing the entire string. Once match is found, it uses the remainder of the string to try and apply another match.

What is preg_ match()?

Definition and Usage. The preg_match() function searches string for pattern, returning true if pattern exists, and false otherwise. If the optional input parameter pattern_array is provided, then pattern_array will contain various sections of the subpatterns contained in the search pattern, if applicable.

Why use preg_ match in PHP?

Definition and Usage. The preg_match() function returns whether a match was found in a string.


1 Answers

The equivalent in Ruby for preg_match_all is String#scan, like so:

In PHP:

$result = preg_match_all('/some(regex)here/i', 
          $str, $matches);

and in Ruby:

result = str.scan(/some(regex)here/i)

result now contains an array of matches.

And the equivalent in Ruby for preg_replace is String#gsub, like so:

In PHP:

$result = preg_replace("some(regex)here/", "replace_str", $str);

and in Ruby:

result = str.gsub(/some(regex)here/, 'replace_str')

result now contains the new string with the replacement text.

like image 190
Mike Lewis Avatar answered Oct 07 '22 01:10

Mike Lewis