July 2011
Intermediate to advanced
400 pages
8h 46m
English
I said earlier that regular expressions are often used to process data stored in files on disk. In some earlier examples, I read in data from a disk file, did some pattern matching, and displayed the results on the screen. Here is one more example in which I count the words in a file. You do this by scanning each line in order to create an array of words (that is, sequences of alphanumeric characters) and then adding the size of each array to the variable, count:
wordcount.rb
count = 0
File.foreach( 'regex1.rb' ){ |line|
count += line.scan( /[a-z0-9A-Z]+/ ).size
}
puts( "There are #{count} words in this file." )If you want to verify that the word count is correct, you could display a numbered list of words read in from the file. ...
Read now
Unlock full access