Javascript Regex Negative Look-ahead (Validating EXACTLY {X} Occurrences and Not More) -
i think it's called negative look-ahead /x(?!y)/
, i'm not sure since started doing regex stuff today. i'm trying validate following:
// matches aa-00 through zz-99 var regex = /([a-za-z]{2}(?!\b))((-){1})([0-9]{2}(?!\b))/; var result = regex.test("ev-05"); // should pass console.log("ev-05: " + result + "\n"); result = regex.test("ev-09"); // should pass console.log("ev-09: " + result + "\n"); result = regex.test("ev-11"); // should pass console.log("ev-11: " + result + "\n"); result = regex.test("ev-30"); // should pass console.log("ev-30: " + result + "\n"); result = regex.test("ev03"); // should fail console.log("ev03: " + result + "\n"); result = regex.test("e-17"); // should fail console.log("e-17: " + result + "\n"); result = regex.test("ev-5"); // should fail console.log("ev-5: " + result + "\n"); result = regex.test("evv-36"); // should fail console.log("evv-36: " + result + "\n"); result = regex.test("ev-019"); // should fail console.log("ev-019: " + result + "\n"); result = regex.test("ev--05"); // should fail console.log("ev--05: " + result + "\n");
here's want:
letter#letter#hyphen#digit#digit
(honestly have no idea how describe in readable fashion).
i not want allow input of values of 5 parameters. must 2 letters followed hyphen, followed 2 digits (0-9). want validate there not 3+ letters, nor 3+ digits.
i thought {n} occurrence marker each enough, still returns true
when there 3+ letters/digits (as intention of {n} marker). tried negative look-ahead return false if word \b
found letters, , non-word \b
digits. didn't work either.
if remove negative look-aheads , \b
& \b
, stick the original:
var regex = /[a-za-z]{2}(-){1}[0-9]{2}/;
then half of values valid, ones extra characters/digits considered valid.
long story short: how ensure there exactly x
amount of occurrences something, , return false when there extra? maybe i'm messing nla implementation.
you're making things little more complicated should here. can use this:
/^[a-za-z]{2}-[0-9]{2}$/;
^
match beginning of string , $
match end of string.
this regex allow strings containing 2 letters, followed 1 hyphen , followed 2 digits. can rewrite [0-9]
\d
in javascript.
/([a-za-z]{2}(?!\b))((-){1})([0-9]{2}(?!\b))/;
this doesn't quite work might expect. (?!\b)
prevents word boundary occurring after 2 letters, make valid strings fail.
((-){1})
don't need many parenthesis, if want group those, because there's hardly group. use parentheses capture stuff you'll use later on. {1}
redundant well. have never seen single concrete use of {1}
. {n}
useful when n
greater 1.
([0-9]{2}(?!\b))
again, parentheses not quite useful, here, used negated word boundary, should work (similar $
anywhere in string).
if want match such format anywhere in string, can use word boundaries follows:
/\b[a-za-z]{2}-[0-9]{2}\b/;
Comments
Post a Comment