It's a regular expression question!

Asked 2 years ago, Updated 2 years ago, 50 views

There's a regular expression like this, but I'm not sure what it means. I want to show you this page only when I log in by fixing the following part, so please interpret it!

url(r'^(?P<code_id>[-\w]+)$',views.my_method)

django python

2022-09-22 10:56

2 Answers

I think it's the urls file in the vault. Usually, this url is in the app.Since it's in py, I'll explain the app name assuming it's somename. And let's assume that the connected method is views.my_method as follows.

url(r'^(?P<code_id>[-\w]+)$',views.my_method)

At this time, mysite.com/somename/hi-123-hello When I get a url request, I deliver it to my_method. This is how it's communicated.

 views.my_method(request, code_id='hi-123-hello')

In my_method, you can get code_id with ** kwarg.


2022-09-22 10:56

The regular expression you asked is ^(?P<code_id>[-\w]+)$.

^ means the beginning of a sentence.

The (?P<name>...) form names the group that matches... In this case, code_id would be the name.

$ means the end of the sentence.

The pattern that matches the code_id is [-\w]+.

[...] indicates a set of characters. The characters in this set are - and \w.

\w are characters that represent words. Contains case letters, numbers, and underscores. The regular expression is [a-zA-Z0-9_].

+ means that the preceding pattern is repeated once or more.

Therefore, [-\w]+ matches a string that repeats more than one letter of alphabetic case, number, underscore, and hyphen.

^(P<code_id>[-\w]+)$ will be a regular expression that matches a string that repeats more than one letter with only alphabetic case, number, underscore, and hyphen by the name of code_id from the beginning to the end of the sentence.

For more information on Python regular expressions, see https://docs.python.org/3/library/re.html.


2022-09-22 10:56

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.