Django URL Pattern For Integer

前端 未结 2 976
失恋的感觉
失恋的感觉 2021-01-17 12:09

I\'m new to Python and Django. I added a URLPattern into urls.py as below:

    url(r\'^address_edit/(\\d)/$\', views.address_edit, name = \"address_edit\"),         


        
2条回答
  •  北海茫月
    2021-01-17 13:08

    The RegEx should have + modifier, like this

    ^address_edit/(\d+)/$
    

    Quoting from Python's RegEx documentation,

    '+'

    Causes the resulting RE to match 1 or more repetitions of the preceding RE. ab+ will match a followed by any non-zero number of bs; it will not match just a.

    \d will match any numeric digit (0-9). But it will match only once. To match it twice, you can either do \d\d. But as the number of digits to accept grows, you need to increase the number of \ds. But RegEx has a simpler way to do it. If you know the number of digits to accept then you can do

    \d{3}
    

    This will accept three consecutive numeric digits. What if you want to accept 3 to 5 digits? RegEx has that covered.

    \d{3,5}
    

    Simple, huh? :) Now, it will accept only 3 to 5 numeric digits (Note: Anything lesser than 3 also will not be matched). Now, you want to make sure that minimum 1 numeric digit, but maximum can be anything. What would you do? Just leave the range open ended, like this

    \d{3,}
    

    Now, RegEx engine will match minimum of 3 digits and maximum can be any number. If you want to match minimum one digit and maximum can be any number, then what would you do

    \d{1,}
    

    Correct :) Even this will work. But we have a shorthand notation to do the same, +. As mentioned on the documentation, it will match any non-zero number of digits.

提交回复
热议问题