How to use a regular expression to match a fixed length number with a hyphen in the middle?

I am new to regular expressions and would like to know how to write a regular expression that does the following:

Checks a string like 123-0123456789. Only numeric values ​​and hyphens are allowed. Also, make sure that there are 3 numeric characters and 10 characters after the hyphen before the hyphen.

+3
source share
3 answers

These answers will not work for strings with a large number of digits (for example, "012-0123456789876"), so you need to:

str.match(/^\d{3}-\d{10}$/) != null;

or

/^\d{3}-\d{10}$/.test(str);
+7
source

Try the following:

^\d{3}-\d{10}$

It says: Accept only 3 digits, then a hyphen, then only 10 digits

+2
source

, :

var valid = (str.match(/^\d{3}-\d{10}$/) != null);

:

> s = "102-1919103933";
"102-1919103933"
> var valid = s.match(/\d{3}-\d{10}/) != null;
> valid
true
> s = "28566945";
"28566945"
> var valid = s.match(/\d{3}-\d{10}/) != null;
> valid
false
+2

Source: https://habr.com/ru/post/1792978/


All Articles