Experiments with ruby-processing (processing-2.2.1) and JRubyArt for processing-3.0

Wednesday, 20 March 2013

Demonstrating regex in ruby-processing

There is a example in the vanilla processing distribution, that demonstrates the use of regex (based on java) to extract links from the processing web-site. This more rubified variant extracts only the web addresses using split with a regex. Note this just to demonstrate/explore regex there is the 'uri' module to do this sort of thing if you are serious.
NB: tested with development version of ruby-processing see here.
#
# Regular Expression example
# by Martin Prout.  
# 
# This uses ruby scan
#
# Here we'll load the raw HTML from a URI and search for web-links
#

attr_reader :links, :url

def setup
  size(360, 480)
  @url = "http://processing.org"
  # Load the links
  @links = load_links(url)
  links.uniq! # get rid of the duplicates
  text_font(create_font("Georgia", 16))
end

def draw
  background(0)
  # Display the bare links
  fill(0, 255, 255)
  links.each_with_index do |link, i|
    text(link, 10, 20 + i * 20)
  end
end

def load_links(s)
  result = []
  # Load the raw HTML
  lines = load_strings(s)
  # Put it in one big string
  all_txt = lines.join('\n')
  all_txt.scan(/
        https?:\/\/
        \w+
        (?: [.-]\w+ )*
        (?:
            \/
            [0-9]{1,5}
            \?
            [\w=]*
        )?
    /ix)
end


No comments:

Post a Comment

Followers

Blog Archive

About Me

My photo
I have developed JRubyArt and propane new versions of ruby-processing for JRuby-9.1.5.0 and processing-3.2.2