Home > Back-end >  Urlpattern regular expression not working
Urlpattern regular expression not working

Time:07-25

So i'm trying to make url like so

re_path(r'^product_list/(?P<category_slug>[\w-] )/(?:(?P<filters>[\w~@=] )?)$', views.ProductListView.as_view(), name='filtered_product_list'),

and at this point it works with things like:

/product_list/sdasdadsad231/bruh=1~3~10@nobruh=1~4

bruh=1~3~10@nobruh=1~4 - those are filters

but later i want to implement search by word functionality

so i want it recognize things like

/product_list/sdasdadsad231/?filters=bruh-1~3~10&nobruh-1~4&search_for=athing

/product_list/sdasdadsad231/?filters=bruh-1~3~10&nobruh-1~4

/product_list/sdasdadsad231/?search_for=athing

/product_list/sdasdadsad231/

so in different situations it will get filters and/or search_for or nothing at all

CodePudding user response:

You might write the pattern as:

^product_list/(?P<category_slug>[\w-] )/(?:\??(?P<filters>[\w~@=&-] )?)$

Regex demo

If you want to match the leading / from the example data, you can append that in the pattern after the ^

  • Related