1

Hi I'm always been confused with Regex, and I don't understand the responses to the other help threads.

Basically my question is, can i combine

r'^input/?$'

and

r'^input/index.html?$'

into this?

r'^input(/(index.html?)?)?$'

In Django, I get this error:

input() takes exactly 1 argument (3 given)

It only gives the error when it matches correctly, so maybe it's not a regex problem?

2 Answers 2

1

Personally, I would prefer not to combine the two regular expressions. I think that having two url patterns,

url(r'^input/?$', input, name="input"),
url(r'^input/index.html?$', input),

is more readable than one.

However, if you do want to combine the two, you can use non-capturing parentheses:

r'^input(?:/(?:index.html?)?)?$'

A quick example might help explain:

>>> import re
>>> # first try the regex with capturing parentheses
>>> capturing=r'^input(/(index.html?)?)?$'
>>> # Django passes the two matching strings to the input view, causing the type error
>>> print re.match(capturing, "input/index.html").groups()
('/index.html', 'index.html')
>>> # repeat with non capturing parentheses
>>> non_capturing=r'^input(?:/(?:index.html?)?)?$'
>>> print re.match(non_capturing, "input/index.html").groups()
()

See the Regular Expression Advanced Syntax Reference page for more info.

Sign up to request clarification or add additional context in comments.

Comments

0

If you use this in your urlpatterns you don't need to write ? symbol because everything that comes after that you can parse in your view function. And the request to /input/index.html?param=2 will be correctly processed with r'^input/index.html$' regex. Then in the view function you can obtain parameters like so:

def my_view(request):
    param = request.GET.get('param', 'default_value')

Find more info here: https://docs.djangoproject.com/en/1.9/topics/http/urls/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.