Lecture 04
Lecture 04
/ the shop\ . $ / Wildcard expression i.e. can She went to the shop.
match any character (except
a carriage return)
/ \b the \b / Matches a word boundary She went to the shop to buy the
birthday card for them.
/ \W/
/ ˽\t\n\r\f\v/ Whitespace, space,
tab
/ \s/
/^\s/ Non-whitespace
/ \S/
import re
import re
pattern = ‘[pP]ython’
import re
pattern = ‘[pP]ython’
text_string = “I love Python.”
Example 01 Example 02
import re text_string = “Python is my favourite.”
text_string = “I love Python.” x = re.match(“[pP]ython”, text_string)
x = re.match(“[pP]ython”, text_string) print(x)
print(x) Output
Output <_sre.SRE_Match object; span=(0, 6),
match='Python'>
None
Process finished with exit code 0
Process finished with exit code 0
• https://www.w3schools.com/python/python_regex
.asp
• https://docs.python.org/3/library/re.html
• https://docs.python.org/3/howto/regex.html
Lecture 03 Regular Expressions {regex} 17
Summing Up
• Regular expressions are good at representing
subsets of natural language
• But may be difficult for humans to understand for
any real (large) subset of a language
• Can be hard to scale up: e.g., when many choices at any
point (e.g. surnames)
• But quick, powerful and easy to use for small problems