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!
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.
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.
Definition and Usage. The preg_match() function returns whether a match was found in a string.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With