I am trying to create a URL dispatcher whic detects [a-zA-Z] chars (one word) and nothing at all.

I tried something like this, but the nothing does not work, only the chars.

url(r'(?P<search_word>[a-zA-Z].*?)/?$', 'website.views.index_view', name='website_index'),

What am i missing?

有帮助吗?

解决方案

I think you want something like this instead (note the lack of a dot after [a-zA-Z]):

ur'^(?P<search_word>[a-zA-Z]*)/?$'

In your original regex, .*? will allow for any character(s) (even spaces, for example). Also, [a-zA-Z] will only match a single character unless it is followed by an * or a +.

Here is an example of my regex using the re module:

>>> import re
>>> re.match(ur'^(?P<search_word>[a-zA-Z]*)/?$', 'testString/')
<_sre.SRE_Match object at 0x02BF4F20>  # matches 'testString/'
>>> re.match(ur'^(?P<search_word>[a-zA-Z]*)/?$', 'test-String/')  # does not match 'test-String/' because of the hyphen
>>> re.match(ur'^(?P<search_word>[a-zA-Z]*)/?$', '')  # also matches empty string ''
<_sre.SRE_Match object at 0x02BF44A0>
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top