Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django URL regular expression: make URL tolerate int or float values

the url format is: domain/startValue/endValue/content

here, startValue and endValue take either int or float numbers..

i tried: /(\d+)/(\d+) which takes int values

and:

/(\d+\.\d+)/(\d+\.\d+) which takes float values

but don't know how to put them together which takes both formats of numbers

tried:

 /(\d+)|(\d+\.\d+)/(\d+)|(\d+\.\d+)

was told by browser that url does not match view function parameters

thanks for any advice!

like image 495
Simon Avatar asked Dec 13 '25 01:12

Simon


2 Answers

Since you're alway starting with ints, simply make the float part optional using the ? regex operator, and use a non-capturing group:

intorfloat_re = "(\d+(?:\.\d+)?)"

..and use that string in your url definition.

like image 67
brianz Avatar answered Dec 14 '25 19:12

brianz


I Am aware this is already answered and accepted, but looking for the right regex, this one passed my path. So a little adjustment on the given and accepted answer:

use

intorfloat_positiveornegative_re = "(-?\d+(?:\.\d+)?)"

if you want it to accept both negative or positive integers or floats

By the way, I combined this answer with the answer to this question: Regex to match a negative number in Django URL dispatcher?

like image 45
michel.iamit Avatar answered Dec 14 '25 17:12

michel.iamit



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!