I have been avoiding regex for years as I find it very intimidating, however it seems this is a necessary skill to learn to build real things, I have real use cases to match for routes, access-lists and interfaces of routers and firewalls.
Here is a code snippet for the regex block, in this code snippet i have a collection of regex files for practice, the files are from the udemy instructor Sujith George on his course: The Complete Regular Expressions Course:Beginner to Advanced, he uses javascript to match the regex.
import re from os.path import exists path = "" # file path pattern = "(fooa*bar)" # change the pattern as necessary file = "regex01.txt" # change filename as necessary # Check for file existence if exists(path + file): with open(path + file, "r") as file: rows = file.read() # read the entire text file and store in rows object. regex = re.compile(pattern) # construct a regex object with regex. for row in rows.split(): # test on every row to find match if regex.search(row): # if a match is found print the row print(row)
Another code which uses list comprehension.
import re from os.path import exists path = "" # file path pattern = "(fooa*bar)" # change the pattern as necessary file = "regex01.txt" # change filename as necessary # Check for file existence if exists(path + file): with open(path + file, "r") as file: rows = file.read() # read the entire text file and store in rows object. regex = re.compile(pattern) print([row for row in rows.split() if regex.search(row)])