Ruby - String match method

Introduction

=~ returns the position of the first match or nil depending on whether the regular expression matches the string.

String match method provides a lot more power.

Demo

puts "String has vowels" if "This is a test".match(/[aeiou]/)

Result

In regular expressions, if you surround a section of the expression with parentheses ( and ), the data matched is made available separately from the rest.

match method lets you access this data:

Demo

x = "This is a test".match(/(\w+) (\w+)/) 
puts x[0] # from   ww w.  ja  v a 2s .  co  m
puts x[1] 
puts x[2]

Result

match method returns a MatchData object that can be accessed like an array.

The first element (x[0]) contains the data matched by the entire regular expression.

Related Topic