简体   繁体   中英

regex match numbers with potential letters

I need to match with JS:

  • a number,
  • which potentially can be followed by a letter (or two),
  • and may be separated by a space
  • or hyphen

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 )+$

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.

Aaaaand, mine is a hybrid of the other answers. :)

 /^\\d+[ -]?[az]{0,2}$/i 
  • \\d+ = 1 or more digits
  • [ -]? = an optional space character (note: space only, not "whitespace") or dash
  • [az]{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 [az] 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
  • [az]{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 [az] 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.

会做吗?

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

(^[0-9]+( |-){0,1}[a-zA-Z]{0,2})

您可以在http://gskinner.com/RegExr/中进行测试,这是测试和了解RegEx的非常有用的工具

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM