Reputation: 12512
I need to match with JS:
For example:
23
4545a
1B
554 cs
34-S
Regex is not my strong suit, so all I've got is this...
^[0-9A-Za-z ]+$
UPDATED:
^(0-9A-Za-z )+$
Upvotes: 0
Views: 521
Reputation: 7940
Aaaaand, mine is a hybrid of the other answers. :)
/^\d+[ -]?[a-z]{0,2}$/i
\d+
= 1 or more digits[ -]?
= an optional space character (note: space only, not "whitespace") or dash[a-z]{0,2}
= 1 or 2 alpha characters (note: lowercase only at the moment, but keep reading . . .)i
at the end of the pattern makes it case insensitive, so the [a-z]
will match upper or lower-case alphasEDIT - Okay, so I found an error in all of our answers. LOL Because the alpha pattern allow 0 characters at the end and the space and dash are optional, the regexes that we've provided so far result in a false positive for the following test data: 123-
and 456 <--- with a space at the end
The second one could be resolved by using $.trim()
on the value (if that is allowed for what you are trying to test), but the first one can't.
So . . . that brings us to a new regex to handle those situations:
/^\d+([ -]?[a-z]{1,2})?$/i
\d+
= 1 or more digits[ -]?
= an optional space character (note: space only, not "whitespace") or dash[a-z]{1,2}
= must have 1 or 2 alpha characters (note: lowercase only at the moment, but keep reading . . .)( . . . )?
around those last two patterns enforces that the space or dash is only valid after the numbers, IF they are, then, followed by the 1 or 2 letters . . . however, that entire group is optional, as a whole.i
at the end of the pattern makes it case insensitive, so the [a-z]
will match upper or lower-case alphasThey updated regex matches all of the examples and fails on the two invalid cases that I mentioned, as well.
Note: If numbers followed by just a space should be considered valid, trimming the value before you test it will allow that case to pass as well.
Upvotes: 2
Reputation: 136074
A little verbose perhaps but demonstrates the required parts I think
[0-9]+[\s-]{0,1}[a-zA-Z]{0,2}
Equates to:
This regex matches each of your test scenarios.
Upvotes: 2
Reputation: 21
(^[0-9]+( |-){0,1}[a-zA-Z]{0,2})
You can test it in http://gskinner.com/RegExr/, a very useful tool to test and understand RegEx
Upvotes: 1