1

I am doing some basic validation. The flow of the program goes like:

  • User inputs a string
  • Clicks SUBMIT

Now I want to make sure the following rules are fulfilled:

  • No spaces
  • Must be alphanumeric... no special charatcers! (ie !@#$%^&*)
  • Must start with a letter
  • Must be at least 3 characters

How can I do this using python/django regular expressions?

Please Help

2
  • did you mean "Must be at least 3 digits" or "Must be at least 3 characters"? Commented Dec 2, 2011 at 14:39
  • at least 3 characters (e.g. xxx is valid) Commented Dec 2, 2011 at 14:50

2 Answers 2

6

You can do this in Python without regular expressions:

if a.isalnum() and a[0].isalpha() and len(filter(str.isdigit, a)) >= 3:
    ...

If according to @Toomai "3 digits" are "at least 3 characters long", then this is what you need:

if a.isalnum() and a[0].isalpha() and len(a) >= 3:
    ...
Sign up to request clarification or add additional context in comments.

3 Comments

If the question means "at least 3 characters long" and not "includes at least 3 numbers", then you can get rid of the filter.
@Toomai - added the other alternative too.
@eumiro: what if we have to include '-' and '_' (dash and underscore) to the list, wont a.isalnum() be a hassle?
3

Try this

re.compile("^[A-Za-z]\w{2,}$")

>>> re.compile("^[A-Za-z]\w{2,}$")
<_sre.SRE_Pattern object at 0x0272C158>
>>> expr=re.compile("^[A-Za-z]\w{2,}$")
>>> expr.match("A12345")
<_sre.SRE_Match object at 0x02721288>
>>> expr.match("A1")
>>> expr.match("1AS")
>>> expr.match("AB1")
<_sre.SRE_Match object at 0x0272E138>
>>> expr.match("ab1")
<_sre.SRE_Match object at 0x02721288>
>>> expr.match("Abhijit$%^&#@")
>>> 

5 Comments

this does not handle the case for special characters
example "Abhijit@#%" is true. As point 2 says no special characters except for dash ('-') and underscore ('_')
Sry about that. Just add a $ at the end like re.compile("^[A-Za-z]\w{2,}$")
I have modified my post accordingly

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.