Pavan
Pavan

Reputation: 583

Javascript regex for Phone Number

I did the work and wrote the following regex:

/^([0-9.]+)$/

This is satisfying for the following conditions:

123.123.123.132
123123213123

Now I need add one more feature for this regex that it can have one alphabet in the Phone Number like

123.a123.b123.123

but not

123.aa1.bb12

I tried with

/^([0-9.]+\w{1})$/

It can contain only one alphabet between the .(dot) symbol. Can someone help me on this !!!

Thanks in Advance !!

Upvotes: 3

Views: 86

Answers (1)

The fourth bird
The fourth bird

Reputation: 163632

The pattern that you use ^([0-9.]+)$ uses a character class which will match any of the listed characters and repeats that 1+ times which will match for example 123.123.123.132.

This is a bit of a broad match and does not take into account the position of the matched characters.

If your values starts with 1+ digits and the optional a-z can be right after the dot, you might use:

^\d+(?:\.[a-zA-Z]?\d+)*$

Explanation

  • ^ Start of the string
  • \d+ Match 1+ digits
  • (?: Non capturing group
    • \.[a-zA-Z]?\d+ Match a dot followed by an optional a-zA-Z and 1+ digits
  • )* Close group and repeat 0+ times
  • $ End of the string

See the regex101 demo

Upvotes: 2

Related Questions