santa
santa

Reputation: 12512

regex match numbers with potential letters

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

Answers (4)

talemyn
talemyn

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 . . .)
  • The i at the end of the pattern makes it case insensitive, so the [a-z] will match upper or lower-case alphas

EDIT - 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 . . .)
  • The ( . . . )? 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.
  • The i at the end of the pattern makes it case insensitive, so the [a-z] will match upper or lower-case alphas

They 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

Jamiec
Jamiec

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:

  • Any character in the class [0-9], 1 or more repetitions
  • Whitespace or a hyphen, 0 and 1 repetitions
  • Any character in the class [a-zA-Z], 0 to 2 repetitions.

This regex matches each of your test scenarios.

Upvotes: 2

Edi Eco
Edi Eco

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

Sithsu
Sithsu

Reputation: 2219

Will following do?

^[0-9]+( |-)?[A-Za-z]{0,2}$

Upvotes: 1

Related Questions