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.
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.
\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).
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.
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.
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);
Try this:
^\d{3}-\d{10}$
This says: Accept only 3 digits, then a hyphen, then only 10 digits
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With