MC logo

Regular Expressions II

  Ruby Example Code

<<Regular Expressions I re2.rb More List Ops>>
# Using re's to break up a line.
print "Please enter a line: "
line = gets.chomp

res = [ ]
while res != ''
    # String leading blanks.
    line.sub!(/^\s*/, '')

    break if line == ''

    # See what the leading is for next action.
    if line[0].chr == '"' then
        # Quoted.
        line.sub!(/^"([^"]*)"/, '')
        res.push($1)
    elsif line.sub!(/^(\d+):(\S+)/, '')
        # Repeated with n:
        $1.to_i.times { res.push($2) }
    else
        # Just a word.
        line.sub!(/^(\S+)/, '')
        res.push($1)
    end

end

res.each { |x| print "  [", x, "]\n" }

The sub and sub! methods of String match their first argument (a regular expression), and replace the portion matched with their second (a string).

This program breaks up the input line into words, with two special notations. Double-quoted sections are obeyed, which can contain spaces, and a word can be repeated by placing a count and a colon before it, like 5:fred instead of typing fred five times.
<<Regular Expressions I More List Ops>>