Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 !!

like image 927
Pavan Avatar asked Dec 03 '25 03:12

Pavan


1 Answers

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

like image 136
The fourth bird Avatar answered Dec 06 '25 05:12

The fourth bird



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!