[英]regex match numbers with potential letters
I need to match with JS: 我需要搭配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 )+$
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. 此正则表达式匹配您的每个测试方案。
Aaaaand, mine is a hybrid of the other answers. 亚伦,我的是其他答案的混合体。 :) :)
/^\\d+[ -]?[az]{0,2}$/i
\\d+
= 1 or more digits \\d+
= 1个或更多数字 [ -]?
= 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 . . .) [az]{0,2}
= 1或2个字母字符(请注意:此刻仅小写,但请继续阅读。。。) i
at the end of the pattern makes it case insensitive, so the [az]
will match upper or lower-case alphas i
使其不区分大小写,因此[az]
将匹配大写或小写字母 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
大声笑因为字母模式的末尾允许使用0个字符,并且空格和破折号是可选的,所以到目前为止,我们提供的正则表达式会导致以下测试数据的误报:
123-
和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. 第二个可以通过在值上使用
$.trim()
来解决(如果您尝试测试的值允许),但是第一个不可以。
So . 这样。 .
。 .
。 that brings us to a new regex to handle those situations:
这使我们进入了一个新的正则表达式来处理这些情况:
/^\d+([ -]?[a-z]{1,2})?$/i
\\d+
= 1 or more digits \\d+
= 1个或更多数字 [ -]?
= 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 . . .) [az]{1,2}
=必须包含1或2个字母字符(注意:此刻仅小写,但请继续阅读。。。) ( . . . )?
( . . . )?
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 . i
at the end of the pattern makes it case insensitive, so the [az]
will match upper or lower-case alphas i
使其不区分大小写,因此[az]
将匹配大写或小写字母 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的非常有用的工具
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.