CHAPTER SIXTEEN
285
regex2.rb aStr = "HELLO WORLD" case aStr when /^[a-z 0-9]*$/ puts( "Lower case" ) when /^[A-Z 0-9]*$/ puts( "Upper case" ) else puts( "Mixed case
" ) end Often regular expressions are used to process the text in a file on disk. Let’s suppose, for example, that you want to display all the full-line comments in a Ruby file but omit all the code or partial line-comments. You could do this by trying to match from the start of each line (^) zero or more whitespace characters (a whitespace character is represented by s) up to a comment character (‘#’): regex3a.rb # displays all the full-line comments in a Ruby file File.foreach( 'regex1.rb' ){ |line| if line =~ /^s*#/ then puts( line ) end }
MATCH GROUPS
You can also use a regular expression to match one or more substrings. In order to do this, you should put part of the regular expression between round brackets. Here I have two groups (sometimes called ‘captures’), the first tries to match the string ‘hi’, the second tries to match a string starting with ‘h’, followed by any three characters (a dot means ‘match any single character’ so the three dots here will match any three consecutive characters) and ending with ‘o’: