reading-notes

My reading notes journal for Code Fellows

View the Project on GitHub

Read Class 19: Automation

Python Regex

Regex are a sequence of characters used to check whether a pattern exists in a given text (string) or not.

To import regex:

  import re

Ordinary characters can be used to perform simple exact matches:

pattern = r"Cookie" sequence = "Cookie" if re.match(pattern, sequence): print("Match!") else: print("Not a match!")

Match!

The match() function returns a match object if the text matches the pattern. Otherwise, it returns None.

Special characters are characters that do not match themselves as seen but have a special meaning when used in a regular expression. For simple understanding, they can be thought of as reserved metacharacters that denote something else and not what they look like.

. - A period. Matches any single character except the newline character.

re.search(r'Co.k.e', 'Cookie').group()

'Cookie'

^ - A caret. Matches the start of the string.

This is helpful if you want to make sure a document/sentence starts with certain characters.

re.search(r'^Eat', "Eat cake!").group() ## However, the code below will not give the same result. Try it for yourself: # re.search(r'^eat', "Let's eat cake!").group()

'Eat'

$ - Matches the end of string.

This is helpful if you want to make sure a document/sentence ends with certain characters.

re.search(r'cake$', "Cake! Let's eat cake").group() ## The next search will return the NONE value, try it: # re.search(r'cake$', "Let's get some cake on our way home!").group()

'cake'

[abc] - Matches a or b or c.
[a-zA-Z0-9] - Matches any letter from (a to z) or (A to Z) or (0 to 9).

re.search(r'[0-6]', 'Number: 5').group()

'5'


## Matches any character except 5 re.search(r'Number: [^5]', 'Number: 0').group() ## This will not match and hence a NONE value will be returned #re.search(r'Number: [^5]', 'Number: 5').group()


'Number: 0'

Cited from: https://www.datacamp.com/tutorial/python-regular-expression-tutorial

Things I want to know more about

Honestly the whole concept of regex still gives me trouble I think I finally understand it then I run into another issue which then confuses me but I’ll just keeping digging for information to better understand the topic.

References