2

I am working on writing a regex for phonenumber. I have made a very basic regex for matching a phone number.

^[-+[:blank:][:digit:]]*$. 

But that one in not working in python. If I try the same regex on someother tool for example text edit for regex search then its working. I am pretty new to regex so will be great if I can get some help.

Thanks

4
  • what are the exact allowed chars in your phone number other than digits? Commented Apr 15, 2013 at 12:29
  • 1
    Does Python support [:blank:][:digit:]? If not, you may want to replace them with [-+ \d]. Commented Apr 15, 2013 at 12:30
  • It only allows - and + Commented Apr 15, 2013 at 12:31
  • Is there supposed to be a period at the end of the line? Commented Apr 15, 2013 at 12:33

1 Answer 1

3

try this (say your allowed phone no length is 10 to 15 digits):

/^[0-9\-\+\s]{10,15}$/

.

This will allow in:

1) numbers (0-9)

2) space

3) dash sign "-"

4) plus sign "+"

This is not a strict enforcing. To have exact strict format, you may need to alter as per your need.

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

5 Comments

Additional information: docs.python.org/2/library/re.html#regular-expression-syntax is a good way to start, for instance + is an operator and must be escaped ;)
I did that but since I am new to stackoverflow and my reputation is just 1 so I cant voteup. :(
@Torxed, the plus sign doesn't need escaping when it's inside a character class. Neither does the hyphen, if you place it carefully. [0-9+\s-] works just fine.
@AlanMoore what do you know, it works :) Thank you for pointing that out :)
escaping doesnt cause any error. Even if not needed, its better to use it just to be sure.

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.