THE BOOK OF RUBY
puts( /abc/ =~ 'xyzabcxyzabc' ) #=> returns 3 puts( /abc/ =~ 'xycab' ) #=> returns nil
You can also specify a group of characters, between square brackets, in which case a match will be made with any one of those characters in the string. Here, for example, the first match is made with ‘c’ and that character’s position in the string is returned: puts( /[abc]/ =~ 'xycba' ) #=> returns 2
While I’ve used forward slash delimiters in the examples above, there are alter-native ways of defining regular expressions: you can specifically create a new Regexp object initialized with a string or you can precede the regular expression with %r and use custom delimiters - non alphanumeric characters - as you can with strings (see Chapter 3). In the example below, I use curly brace delimiters: regex1.rb regex1 = Regexp.new('^[a-z]*$') regex2 = /^[a-z]*$/ regex3 = %r{^[a-z]*$} Each of the above, define a regular expression that matches an all-lowercase string (I’ll explain the details of the expressions shortly). These expressions can be used to test strings like this: def test( aStr, aRegEx ) if aRegEx =~ aStr then puts( "All lower case" ) else puts( "Not all lower case" ) end end test( "hello", regex1 ) #=> matches: "All lower case" test( "hello", regex2 ) #=> matches: "All lower case" test( "Hello", regex3 ) #=> no match: "Not all lower case"
282