CS 3723
 Programming Languages 
  RE: /ab|aac/  


Ruby Program to Search a String for a Match: In this example we want to use a regular expression to search for either "ab" or "aac" in an input string. In case the search is successful, we want to know what came before the match, what matched, and what came after the match. We also want to know if the search was not successful.

Below is a simple Ruby program to carry this out. The regular expression to use is called "r" and the string to search is called "s", an input line of data. (Ruby requires lower-case letters because a variable with an initial upper-case letter should be a constant.) In the output below, the matched data (if any) is red. What comes before the match is yellow, and what comes after is green.

Ruby Program Using Reg. Expr:  /ab|aac/ Output Data (boldface = data entered)
#!/usr/bin/ruby

r = /ab|aac/ # find either "ab" or "aac"

while s = gets  # loop as in Perl
  print "s: ", s
  m = r.match(s) # Ruby's O-O reg. exprs.
  if m != nil
    print "pre_match: ",  m.pre_match
    print ", match: ", m[0]
    print ", post_match: ", m.post_match, "\n"
  else
    print "no match", "\n"
  end
end
cccaabaccc
s: cccaabaccc
pre_match: ccca, match: ab, post_match: accc

cccacaccaaacabcc
s: cccacaccaaacabcc
pre_match: cccacacca, match: aac, post_match: abcc

bbbaccc
s: bbbaccc
no match

bacbabccaaccbb
s: bacbabccaaccbb
pre_match: bacb, match: ab, post_match: ccaaccbb

bacbaaccabcc
s: bacbaaccabcc
pre_match: bacb, match: aac, post_match: cabcc

The last two example inputs show that Ruby uses the first match that comes along.


Revision date: 2013-08-03. (Please use ISO 8601, the International Standard.)