1

How can I construct regx to validate phone number? That is:

  1. First digit must be 04 or 050 , length range between 8-13
  2. First digit cannot be 43 or 44 , first digit must be 4 or 9 and length should be 8 digits

I have tried this pattern:

^[04,050]\\d{8,13} 

Can any body help me?

3

1 Answer 1

3

Let's break it down (hoping I understand correctly):

^               # Start of string
(?:             # Match one of the following:
 04\d{6,11}     # Either an 8-13 digit number starting with 04
|               # or
 050\d{5,10}    # an 8-13 digit number starting with 050
|               # or
 4[0-25-9]\d{6} # an 8 digit number starting with 4 but not 43 or 44
|               # or
 9\d{7}         # an 8 digit number starting with 9
)               # End of alternation
$               # End of string
Sign up to request clarification or add additional context in comments.

7 Comments

I noticed you did thus before and I let it slide, but this time I'm going to pull you up: (?: does not mean "either", although saying so helps make your comments into a sentence, this fact carries no technical weight and may be misleading to novices.
@Bohemian: I'm aware of the potential for misunderstanding. I just don't know what to write instead that's both correct and understandable. How do you like the new version?
I respect your regex skills greatly, however the comments are just wrong. For starters, you are starting a group to allow an OR, that's what the bracket does, then you (unnecessarily) make it non-capturing with ?:, presumably for "performance" reasons (optimising early?), then you introduce some or'ed terms. I would comment it basically like that
Hi Tim Pietzcker , thanks. It worked for me :) This is what I expect .... ^(?:04\\d{6,11}|050\\d{5,10}) and ^(?:4[0-25-9]\\d{6}|9\\d{7}) . Thank you once again !!
I would have just said (?: # start of (non capturing) group. Now, a serious comment - why have the group at all? Isn't it not needed? Won't the OR work anyway because it's "bracketed" by start/end of input?
|

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.