COMP2021 Lab3: Regular Expressions and its Unix Utilities


Regular Expression

Give the regular expression that matches the requirments.

We can see some examples here.

Task1

Match the pattern "xxx.xxx.xxx.xxx", "xxx" can be any number between 0 and 999.

Task2

Match all the IPv4 address in the form of "xxx.xxx.xxx.xxx", "xxx" can be any number between 0 and 255.

Task3

Matches a date in yyyy-mm-dd format between 1900-01-01 and 2099-12-31, with the separator "-".

Task4

Matching a decimal numbers, you have to deal with positive and negative numbers, significant digits, exponents, and different representations (like the comma used to separate thousands and millions).

You can try your solution here with our example.

And you can find the answer here.


Unix Command: grep

First we download the files demo1.txt and demo2.txt and put them in the working directory.

The basic usage of grep command is to search for a specific string in the specified file as shown below.

grep "this" demo1.txt

You can check for the given string in multiple files.

grep "this" demo*

Case insensitive search using grep -i

grep -i "the" demo1.txt

Match regular expression in files

grep "lines.*empty" demo1.txt

Checking for full words, not for sub-strings using grep -w

grep -i "is" demo1.txt
grep -iw "is" demo1.txt

Displaying lines before/after/around the match using grep -A, -B and -C

grep -A 3 -i "example" demo2.txt
grep -B 2 "single WORD" demo2.txt
grep -C 2 "Example" demo2.txt

Highlighting the search using GREP_OPTIONS

export GREP_OPTIONS='--color=auto' GREP_COLOR='100;8'
grep "this" demo1.txt

You may also try other options such as "v" "c" "l" "o" "b" and "n".

More examples can be found here and here.


Any inquiry please contact your TA by email