Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

Validates a string like 123-0123456789. Only numeric values and a hyphen should be allowed. Also, verify that there are 3 numeric chars before the hyphen and 10 chars after the hyphen.

like image 250
user622683 Avatar asked Feb 18 '11 06:02

user622683


People also ask

How do you match a hyphen in regex?

In regular expressions, the hyphen ("-") notation has special meaning; it indicates a range that would match any number from 0 to 9. As a result, you must escape the "-" character with a forward slash ("\") when matching the literal hyphens in a social security number.

How do you match a regular expression with digits?

\d (digit) matches any single digit (same as [0-9] ). The uppercase counterpart \D (non-digit) matches any single character that is not a digit (same as [^0-9] ). \s (space) matches any single whitespace (same as [ \t\n\r\f] , blank, tab, newline, carriage-return and form-feed).

What do you use in a regular expression to match any 1 character or space?

Use square brackets [] to match any characters in a set. Use \w to match any single alphanumeric character: 0-9 , a-z , A-Z , and _ (underscore). Use \d to match any single digit. Use \s to match any single whitespace character.

What is ?! In regex?

Definition and Usage. The ?! n quantifier matches any string that is not followed by a specific string n. Tip: Use the ?= n quantifier to match any string that IS followed by a specific string n.


3 Answers

The given answers won't work for strings with more digits (like '012-0123456789876'), so you need:

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

or

/^\d{3}-\d{10}$/.test(str);
like image 184
KooiInc Avatar answered Oct 18 '22 00:10

KooiInc


Try this:

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

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

like image 5
Joe Avatar answered Oct 17 '22 22:10

Joe


Sure, this should work:

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

Example:

> 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
like image 2
Jacob Relkin Avatar answered Oct 17 '22 23:10

Jacob Relkin