Regular Expressions:
Summary of Metacharacters
Special Characters | Usage |
. | Matches any single character (except newline). |
* | Matches any number (including zero) of the single character (including a character specified by a regular expression) that immediately precedes it. |
[...] | Matches any one of the class of characters enclosed between the brackets. A hyphen (-) is used to indicate a range of characters. |
[^...] | Matches any character except one of the class of characters enclosed between the brackets. A hyphen (-) is used to indicate a range of characters. |
^ | Matches the beginning of a string or line. |
$ | Matches the end of a string or line. |
\ | Escapes the special character that follows. |
+ | Matches one or more occurrences of the preceding regular expression. |
? | Matches zero or one occurrences of the preceding regular expression. |
| | Specifies that either the preceding or following regular expression can be matched |
() | Groups regular expressions. |
Examples:
===============================================
% cat text
Hello.
Hi.
$6.50 is a good deal for those course notes!
Study hard, and you'll do well.
Student1
Student_A
Student_B
student_c
My dog has no nose.
My dog studies hard
University of Toronto
U of T
===============================================
% egrep 'Student.' text
Student1
Student_A
Student_B
===============================================
% egrep '^Student.' text
Student1
Student_A
===============================================
% egrep '^Student.$' text
Student1
===============================================
% egrep '^Student..' text
Student_A
===============================================
% egrep 'Stu*' text
Study hard, and you'll do well.
Student1
Student_A
Student_B
===============================================
% egrep '[Ss]tudent' text
Student1
Student_A
Student_B
student_c
===============================================
% egrep '[Ss]tudent_[A-Z]' text
Student_A
Student_B
===============================================
% egrep '[Ss]tudent_[a-z]' text
student_c
===============================================
% egrep '[Ss]tudent_[A-Za-z]' text
Student_A
Student_B
student_c
===============================================
% egrep '[Ss]tud[^y]' text
Student1
Student_A
Student_B
student_c
My dog studies hard
===============================================
% egrep '\$6\.50' text
$6.50 is a good deal for those course notes!
===============================================
% egrep 'Student[1-9]+' text
Student1
===============================================
% egrep 'Student[1-9]?' text
Student1
Student_A
Student_B
===============================================
% egrep 'Hello|Hi' text
Hello.
Hi.
===============================================
% egrep 'U(niversity)? of T(oronto)?' text
University of Toronto
U of T
===============================================
% egrep '[Ss]tud(y|ies)' text
Study hard, and you'll do well.
My dog studies hard
===============================================