1 Regular Expressions

Regular expressions are used by editors (ed, ex, vi, sed),grep and awk.

Simplest regular expressions are simply strings, between /'s.

    /hello/
    /ing/
    /or something with spaces/

Many characters - . * [ ] ^ $ \ \( \) \< \>\ - have special meanings in regular expressions.

. matches any character
* matches zero or more of preceding character
[abc] matches one of a or b or c
[a-m] matches one of characters in the inclusive range
[^abc] matches one of characters in not in range
^ matches start of line
$ matches end of line
\ used to escape next character except ...
\< matches beginning of word
\> matches end of word
\(abc\) matches and remembers abc
 

Examples of regular expressions as vi substitution search patterns.

/e.dy/ matches Freddy ready
/a*b/ matches able ebbing
/p[aeiu]n/ matches penny
/[a-zA-Z]/ matches and alphabetic character
/[^a-z]/ matches fred.,was real-time
/[0-9][0-9]*/ matches any positive integer
/a.*b/ matches ab or any characters between
/^and/ matches and at start of line
/ing$/ matches ing at end of line
/^and$/ matches and on line by itself
/\[\/\\\]/ matches [/\]
/\<and\>/ matches the word and

For string replacements in substitute commands, there are some more special characters - & is the matched pattern and \1 is the first remembered match, etc.

s/ing/(&)/ is the same as s/ing/(ing)/

s/.*\(hi\)\(.*\)/\2\1/ throw away up to hi which is remembered

and remember anything following, then reverse them