javascript - regex match numbers with potential letters -
i need match js:
- a number,
- which potentially can followed letter (or two),
- and may separated space
- or hyphen
for example:
23 4545a 1b 554 cs 34-s
regex not strong suit, i've got this...
^[0-9a-za-z ]+$
updated:
^(0-9a-za-z )+$
aaaaand, mine hybrid of other answers. :)
/^\d+[ -]?[a-z]{0,2}$/i
\d+
= 1 or more digits[ -]?
= optional space character (note: space only, not "whitespace") or dash[a-z]{0,2}
= 1 or 2 alpha characters (note: lowercase @ moment, keep reading . . .)- the
i
@ end of pattern makes case insensitive,[a-z]
match upper or lower-case alphas
edit - okay, found error in of our answers. lol because alpha pattern allow 0 characters @ end , space , dash optional, regexes we've provided far result in false positive following test data: 123-
, 456 <--- space @ end
the second 1 resolved using $.trim()
on value (if allowed trying test), first 1 can't.
so . . . brings new regex handle situations:
/^\d+([ -]?[a-z]{1,2})?$/i
\d+
= 1 or more digits[ -]?
= optional space character (note: space only, not "whitespace") or dash[a-z]{1,2}
= must have 1 or 2 alpha characters (note: lowercase @ moment, keep reading . . .)- the
( . . . )?
around last 2 patterns enforces space or dash valid after numbers, if are, then, followed 1 or 2 letters . . . however, entire group optional, whole. - the
i
@ end of pattern makes case insensitive,[a-z]
match upper or lower-case alphas
they updated regex matches of examples , fails on 2 invalid cases mentioned, well.
note: if numbers followed space should considered valid, trimming value before test allow case pass well.
Comments
Post a Comment