regex url definition for slugs and ids
import re
blog_path_1 = '/blog/1/'
blog_path_2 = '/blog/2/'
blog_path_3 = '/blog/34/'
blog_path_4 = '/blog/winter-is-coming/'
matching_digits_regex = r'^/blog/(?P<id>\d+)/$'
def get_id(path):
p = re.compile(matching_digits_regex)
print('{}\'s id is {}'.format(path, p.search(path).group('id')))
get_id(blog_path_1)
get_id(blog_path_2)
get_id(blog_path_3)
try:
get_id(blog_path_4)
except:
print("{} does not have a matching id".format(blog_path_4))
print("\n")
matching_slug_regex = r'^/blog/(?P<slug>[\w-]+)/$'
def get_slug(path):
p = re.compile(matching_slug_regex)
print('{}\'s slug is {}'.format(path, p.search(path).group('slug')))
get_slug(blog_path_1)
get_slug(blog_path_2)
get_slug(blog_path_3)
get_slug(blog_path_4)