Docsity

Regular Expressions - Organization Program Language - Slides | CMSC 330, Study notes of Programming Languages

Toggle sidebar
bg1
1
CMSC 330: Organization of
Programming Languages
More Ruby
CMSC 330 2
Last Lecture
Scripting languages
Ruby language
•Implicit variable declarations
•Many control statements
•Classes & objects
•Strings
CMSC 330 3
Introduction
Ruby language
•Regular expressions
¾Definition & examples
¾Back references
¾Scan
•Arrays
•Code blocks
•Hash
•File
•Exceptions
CMSC 330 4
String Operations in Ruby
•"hello".index("l", 0)
¾Return index of the first occurrence of string in s, starting at n
•"hello".sub("h", "j")
¾Replace first occurrence of "h" by "j" in string
¾Use gsub ("global" sub) to replace all occurrences
•"r1\tr2\t\tr3".split("\t")
¾Return array of substrings delimited by tab
Consider these three examples again
•All involve searching in a string for a certain pattern
•What if we want to find more complicated patterns?
¾Find first occurrence of "a" or "b"
¾Split string at tabs, spaces, and newlines
CMSC 330 5
Regular Expressions
A way of describing patterns or sets of strings
•Searching and matching
•Formally describing strings
¾The symbols (lexemes or tokens) that make up a language
Common to lots of languages and tools
•awk, sed, perl, grep, Java, OCaml, C libraries, etc.
Based on some really elegant theory
•Next lecture
CMSC 330 6
Example Regular Expressions in Ruby
/Ruby/
•Matches exactly the string "Ruby"
•Regular expressions can be delimited by /’s
•Use \to escape /’s in regular expressions
/(Ruby|OCaml|Java)/
•Matches either "Ruby", "OCaml", or "Java"
/(Ruby|Regular)/ or /R(uby|egular)/
•Matches either "Ruby" or "Regular"
•Use ( )’s for grouping; use \to escape ( )’s
pf3
pf4
pf5
pf8

Partial preview of the text

Download Regular Expressions - Organization Program Language - Slides | CMSC 330 and more Study notes Programming Languages in PDF only on Docsity!

CMSC 330: Organization of

Programming Languages

More Ruby

CMSC 330 2

Last Lecture

Scripting languages

Ruby language

  • Implicit variable declarations
  • Many control statements
  • Classes & objects
  • Strings

CMSC 330 3

Introduction

Ruby language

  • Regular expressions ¾ Definition & examples ¾ Back references ¾ Scan
  • Arrays
  • Code blocks
  • Hash
  • File
  • Exceptions

CMSC 330 4

String Operations in Ruby

  • "hello".index("l", 0) ¾ Return index of the first occurrence of string in s, starting at n
  • "hello".sub("h", "j") ¾ Replace first occurrence of "h" by "j" in string ¾ Use gsub ("global" sub) to replace all occurrences
  • "r1\tr2\t\tr3".split("\t") ¾ Return array of substrings delimited by tab

Consider these three examples again

  • All involve searching in a string for a certain pattern
  • What if we want to find more complicated patterns? ¾ Find first occurrence of "a" or "b" ¾ Split string at tabs, spaces, and newlines

CMSC 330 5

Regular Expressions

A way of describing patterns or sets of strings

  • Searching and matching
  • Formally describing strings ¾ The symbols (lexemes or tokens) that make up a language

Common to lots of languages and tools

  • awk, sed, perl, grep, Java, OCaml, C libraries, etc.

Based on some really elegant theory

  • Next lecture

CMSC 330 6

Example Regular Expressions in Ruby

/Ruby/

  • Matches exactly the string "Ruby"
  • Regular expressions can be delimited by /’s
  • Use \ to escape /’s in regular expressions

/(Ruby|OCaml|Java)/

  • Matches either "Ruby", "OCaml", or "Java"

/(Ruby|Regular)/ or /R(uby|egular)/

  • Matches either "Ruby" or "Regular"
  • Use ( )’s for grouping; use \ to escape ( )’s

CMSC 330 7

Using Regular Expressions

Regular expressions are instances of Regexp

  • we’ll see use of a Regexp.new later

Basic matching using =~ method of String

Can use regular expressions in index, search, etc.

line = gets # read line from standard input if line =~ /Ruby/ then # returns nil if not found puts "Found Ruby" end

**offset = line.index(/(MAX|MIN)/) # search starting from 0 line.sub(/(Perl|Python)/, "Ruby") # replace line.split(/(\t|\n| )/) # split at tab, space,

newline**

CMSC 330 8

Using Regular Expressions (cont.)

Invert matching using !~ method of String

  • Matches strings that don't contain an instance of the
regular expression

CMSC 330 9

Repetition in Regular Expressions

/(Ruby)*/

  • {"", "Ruby", "RubyRuby", "RubyRubyRuby", ...}
    • means zero or more occurrences

/Ruby+/

  • {"Ruby", "Rubyy", "Rubyyy", ... }
    • means one or more occurrence
  • so /e+/ is the same as /ee*/

/(Ruby)?/

  • {"", "Ruby"} -? means optional , i.e., zero or one occurrence

CMSC 330 10

Repetition in Regular Expressions

/(Ruby){3}/

  • {“RubyRubyRuby”}
  • {x} means repeat the search for exactly x occurrences

/(Ruby){3,}/

  • {“RubyRubyRuby”, “RubyRubyRubyRuby”, …}
  • {x,} means repeat the search for at least x occurrences

/(Ruby){3, 5}/

  • {“RubyRubyRuby”, “RubyRubyRubyRuby”,
“RubyRubyRubyRubyRuby”}
  • {x, y} means repeat the search for at least x
occurrences and at most y occurrences

CMSC 330 11

Watch Out for Precedence

/(Ruby)*/ means {"", "Ruby", "RubyRuby", ...}

  • But /Ruby*/ matches {"Rub", "Ruby", "Rubyy", ...}

In general

    • {n} and + bind most tightly
  • Then concatenation (adjacency of regular expressions)
  • Then |

Best to use parentheses to disambiguate

CMSC 330 12

Character Classes

/[abcd]/

  • {"a", "b", "c", "d"} (Can you write this another way?)

/[a-zA-Z0-9]/

  • Any upper or lower case letter or digit

/[^0-9]/

  • Any character except 0-9 (the ^ is like not and must
come first)

/[\t\n ]/

  • Tab, newline or space

/[a-zA-Z_$][a-zA-Z_$0-9]*/

  • Java identifiers ($ escaped...see next slide)

CMSC 330 19

Back Reference Example

Extract information from a report

Warning

  • Despite their names, $1 etc are local variables

gets =~ /^Min: (\d+) Max: (\d+)$/ min, max = $1, $

def m(s) s =~ /(Foo)/ puts $1 # prints Foo end m("Foo") puts $1 # prints nil

sets min = $ and max = $

CMSC 330 20

Another Back Reference Example

Warning 2

  • If another search is performed, all back references
are reset to nil
gets =~ /(h)e(ll)o/
puts $
puts $
gets =~ /h(e)llo/
puts $
puts $
gets =~ /hello/
puts $
hello
h
ll
hello
e
nil
hello
nil

CMSC 330 21

Method 2: String.scan

Also extracts substrings based on regular

expressions

Can optionally use parentheses in regular

expression to affect how the extraction is done

Has two forms which differ in what Ruby does

with the matched substrings

  • The first form returns an array
  • The second form uses a code block ¾ We’ll see this later

CMSC 330 22

First Form of the Scan Method

str .scan( regexp )

  • If regexp doesn't contain any parenthesized subparts,
returns an array of matches

¾ An array of all the substrings of str which matched

¾ Note: these string are chosen sequentially from as yet unmatched portions of the string, so while “330 Fall” does match the regular expression above, it is not returned since “330” has already been matched by a previous substring.

**s = "CMSC 330 Fall 2007" s.scan(/\S+ \S+/)

returns array ["CMSC 330", "Fall 2007"]**

CMSC 330 23

First Form of the Scan Method (cont.)

  • If regexp contains parenthesized subparts, returns an
array of arrays

¾ Each sub-array contains the parts of the string which matched one occurrence of the search

¾ Each sub-array has the same number of entries as the number of parenthesized subparts ¾ All strings that matched the first part of the search (or $1 in back-reference terms) are located in the first position of each sub-array

**s = "CMSC 330 Fall 2007" s.scan(/(\S+) (\S+)/) # [["CMSC", "330"],

["Fall", "2007"]]**

CMSC 330 24

Practice with Scan and Back-references

> ls -l drwx------ 2 sorelle sorelle 4096 Feb 18 18:05 bin -rw------- 1 sorelle sorelle 674 Jun 1 15:27 calendar drwx------ 3 sorelle sorelle 4096 May 11 2006 cmsc drwx------ 2 sorelle sorelle 4096 Jun 4 17:31 cmsc drwx------ 1 sorelle sorelle 4096 May 30 19:19 cmsc drwx------ 1 sorelle sorelle 4096 May 30 19:20 cmsc

Extract just the file or directory name from a line using
  • scan
  • back-references

name = line.scan(/\S+$/) # [“bin”]

if line =~ /(\S+$)/ name = $1 # “bin” end

CMSC 330 25

Standard Library: Array

Arrays of objects are instances of class Array

  • Arrays may be heterogeneous a = [1, "foo", 2.14]
  • C-like syntax for accessing elements, indexed from 0 x = a[0]; a[1] = 37

Arrays are growable

  • Increase in size automatically as you access elements irb(main):001:0> b = []; b[0] = 0; b[5] = 0; puts b.inspect [0, nil, nil, nil, nil, 0]
  • [ ] is the empty array, same as Array.new

CMSC 330 26

Standard Library: Arrays (cont.)

Arrays can also shrink

  • Contents shift left when you delete elements a = [1, 2, 3, 4, 5] a.delete_at(3) # delete at position 3; a = [1,2,3,5] a.delete(2) # delete element = 2; a = [1,3,5]

Can use arrays to model stacks and queues

a = [1, 2, 3] a.push("a") # a = [1, 2, 3, "a"] x = a.pop # x = "a" a.unshift("b") # a = ["b", 1, 2, 3] y = a.shift # y = "b"

note: push, pop, shift, and unshift all permanently modify the array

CMSC 330 27

Iterating Through Arrays

It's easy to iterate over an array with while

Looping through all elements of an array is very

common

  • And there’s a better way to do it in Ruby

a = [1,2,3,4,5] i = 0 while i < a.length puts a[i] i = i + 1 end

CMSC 330 28

Iteration and Code Blocks

The Array class also has an each method

  • Takes a code block as an argument

a = [1,2,3,4,5] a.each { |x| puts x }

code block delimited by
{ }’s or do...end
parameter name
body

CMSC 330 29

More Examples of Code Blocks

Sum up the elements of an array

Print out each segment of the string as divided

up by commas (commas are printed trailing

each segment)

  • Can use any delimiter

a = [1,2,3,4,5] sum = 0 a.each { |x| sum = sum + x } printf("sum is %d\n", sum)

s = "Student,Sally,099112233,A" s.each(',') { |x| puts x }

(“delimiter” = symbol used to denote boundaries) CMSC 330 30

Yet More Examples of Code Blocks

  • n.times runs code block n times
  • n.upto(m) runs code block for integers n..m
  • a.find returns first element x of array such that the
block returns true for x
  • a.collect applies block to each element of array and
returns new array (a.collect! modifies the original)

3.times { puts "hello"; puts "goodbye" } 5.upto(10) { |x| puts(x + 1) } [1,2,3,4,5].find { |y| y % 2 == 0 } [5,4,3].collect { |x| -x }

CMSC 330 37

Hash (cont.)

Hash methods

  • values returns array of a hash’s values (in some order)
  • keys returns an array of a hash’s keys (in some order)

Iterating over a hash

italy.keys.each { |key| puts("key: #{key}, value: #{italy[key]}") }

CMSC 330 38

Hash (cont.)

Convenient syntax for creating literal hashes

  • Use { key => value, ... } to create hash table

credits = { "cmsc131" => 4, "cmsc330" => 3, }

x = credits["cmsc330"] # x now 3 credits["cmsc311"] = 3

CMSC 330 39

Standard Library: File

Lots of convenient methods for IO

File.new("file.txt", "rw") # open for rw access f.readline # reads the next line from a file f.readlines # returns an array of all file lines f.eof # return true if at end of file f.close # close file f << object # convert object to string and write to f $stdin, $stdout, $stderr # global variables for standard UNIX IO By default stdin reads from keyboard, and stdout and stderr both write to terminal

File inherits some of these methods from IO

CMSC 330 40

Exceptions

Use begin...rescue...ensure...end

  • Like try...catch...finally in Java

begin f = File.open("test.txt", "r") while !f.eof line = f.readline puts line end rescue Exception => e puts "Exception:" + e.to_s + " (class " + e.class.to_s + ")” ensure f.close end

Class of exception
to catch
Local name
for exception
Always happens

CMSC 330 41

Command Line Arguments

Stored in predefined array variable $*

  • Can refer to as predefined global constant ARGV

Example

  • If ¾ Invoke test.rb as “ruby test.rb a b c”
  • Then ¾ ARGV[0] = “a” ¾ ARGV[1] = “b” ¾ ARGV[2] = “c”

CMSC 330 42

Practice: Amino Acid counting in DNA

Write a function that will take a filename and read

through that file counting the number of times

each group of three letters appears so these

numbers can be accessed from a hash.

(assume: the number of chars per line is a multiple of 3)

gcggcattcagcacccgtatactgttaagcaatccagatttttgtgtataacataccggc catactgaagcattcattgaggctagcgctgataacagtagcgctaacaatgggggaatg tggcaatacggtgcgattactaagagccgggaccacacaccccgtaaggatggagcgtgg taacataataatccgttcaagcagtgggcgaaggtggagatgttccagtaagaatagtgg gggcctactacccatggtacataattaagagatcgtcaatcttgagacggtcaatggtac cgagactatatcactcaactccggacgtatgcgcttactggtcacctcgttactgacgga

CMSC 330 43

Practice: Amino Acid counting in DNA

def countaa(filename) file = File.new(filename, "r") lines = file.readlines hash = Hash.new lines.each{ |line| acids = line.scan(/.../) acids.each{ |aa| if hash[aa] == nil hash[aa] = 1 else hash[aa] += 1 end } } end

initialize the hash, or you will get an error when trying to index into an array with a string

get the file handle

array of lines from the file

for each line in the file

for each triplet in the line

get an array of triplets in the line

CMSC 330 44

Ruby Summary

Interpreted

Implicit declarations

Dynamically typed

Built-in regular expressions

Easy string manipulation

Object-oriented

  • Everything (!) is an object

Code blocks

  • Easy higher-order programming!
  • Get ready for a lot more of this...

Makes it quick to write small programs

Hallmark of scripting languages

CMSC 330 45

Other Scripting Languages

Perl and Python are also popular scripting

languages

  • Also are interpreted, use implicit declarations and
dynamic typing, have easy string manipulation
  • Both include optional “compilation” for speed of
loading/execution

Will look fairly familiar to you after Ruby

  • Lots of the same core ideas
  • All three have their proponents and detractors
  • Use whichever language you personally prefer

CMSC 330 46

Example Perl Program

#!/usr/bin/perl foreach (split(//, $ARGV[0])) { if ($G{$}) { $RE .= "\". $G{$}; } else { $RE .= $N? "(?!\". join("|\",values(%G)). ')(\w)' : '(\w)'; $G{$_} = ++$N; } }

CMSC 330 47

Example Python Program

#!/usr/bin/python import re list = ("deep", "deer", "duck ") x = re.compile("^\S{3,5}.[aeiou]") for i in list: if re.match(x, i): print I else: print