regular expresssion cheat sheet: lecture 3
TRANSCRIPT
-
8/11/2019 Regular Expresssion Cheat Sheet: Lecture 3
1/2
Regular expression cheat sheet:
A regular expression tries to match its characters with any sequence of characters somewhere inanother string. There are a lot of special commands used inside of regular expressions, for which this
sheet can be a reference.
Note: When you see Cor A, assume that Cand Acan be replaced with any character. Whenyou see fooor bar, assume that these can be replaced with arbitrary strings of characters.
Matching:Cmatches with the character C
.matches with any other character
^matches the invisible character at the beginning of a string
$matches the invisible character at the end of a string.
Examples:^Phil$matches with Philbut not with PPhil
Philmatches with aaaaaaaPhilaaa
Carriedoes not match with Alex
^CA.GA.$matches with CATGAG
ca.tdoes not match with CAT
Counting:C*matches with any number of occurrences of the character Cin a row.
C+matches with at least one occurrence of the character Cin a row.
C{n,m}matches between n and m occurrences of Cin a row, inclusive.
C{m} matches at most m occurrences of the character Cin a row.
C?mean that Cis optional. t is equivalent to the regular expression C{,!}
Examples:
"*i*c*h*$matches with ###""""""iihhhhhhh
^*e*%*&*e*n+matches with nP
^!'!{(}?$matches with !'!!
^!'!{),}$does not match with !'!!
Grouping:barcreates an equivalence class of characters baand rt will match with any of them.
-foocreates a group of characters. t will only match with the string fooA/Cmatches everything between Aand C.
^barmatches with everything except for the letters baand r.
-foo0barmatches with either fooor bar.
All the signs associated with counting characters can also be placed after equivalence classes and
groups.
Examples:abca/c%t1matches with cat.
-
8/11/2019 Regular Expresssion Cheat Sheet: Lecture 3
2/2
-Alex0Carrie0Phil0"ichmatches with Phil.
"r{2}i3-ch045?-ch045?matches with "rr"i3ch.
^a/6*will never match with any word made up of only lower case letters.
Escaping:f you want to use a character that is otherwise reserved for some special regular expression command,
you can put a bac!slash -7" in front of it. This is called an escape character. #ince python and theshell both will have confusing behavior when dealing with escape characters, if you want to use themput the character r before the string.
Example:r"7*ichmatches with "*ichbut not with """"""ich.