Regexes exercise 1

Pick up a file with some text in it. Write a script (one for each item) that prints out every line from the file that matches the requirement. You can use the script at the end of the page as a starting point but you will have to change it!

  • has a 'q'
  • starts with a 'q'
  • has 'th'
  • has an 'q' or a 'Q'
  • has a '*' in it
  • starts with an 'q' or an 'Q'
  • has both 'a' and 'e' in it
  • has an 'a' and somewhere later an 'e'
  • does not have an 'a'
  • does not have an 'a' nor 'e'
  • has an 'a' but not 'e'
  • has at least 2 consequtive vowels (a,e,i,o,u) like in the word "bear"
  • has at least 3 vowels
  • has at least 6 characters
  • has at exactly 6 characters
  • all the words with either 'Bar' or 'Baz' in them
  • all the rows with either 'apple pie' or 'banana pie' in them
  • for each row print if it was apple or banana pie?
  • Bonus: Print if the same word appears twice in the same line
  • Bonus: has a double character (e.g. 'oo')

Ruby

examples/ruby/regex_exercise_1.rb

if ARGV.length != 1
    puts "Usage: Needs filename"
    exit
end

fh = open ARGV[0]
fh.each do |line|
    if /REGEX/.match(line)
        print line
    end
end

Python

examples/python/regex_exercise_1.py
#!/usr/bin/env python
from __future__ import print_function

import sys
import re

if len(sys.argv) != 2:
    print("Usage:", sys.argv[0], "FILE")
    exit()

filename = sys.argv[1]
f = open(filename, 'r')

for line in f:
    print(line, end=" ")

    match = re.search(r'REGEX1', line)
    if match:
       print("   Matching 1", match.group(0))

    match = re.search(r'REGEX2', line)
    if match:
       print("   Matching 2", match.group(0))

Perl

For Perl check out the respective regex exercise page on the Perl Maven site.

Solution - Perl 5