[英]Javascript RegEx to Match Against a String
I need to identify strings that have the exact templates (can be either of the two): 我需要确定具有确切模板的字符串(可以是两个模板之一):
This is what I have so far: 这是我到目前为止的内容:
var word = "K4E43057";
if (word.match(/^[A-Za-z]{1,2}[0-9]/g)
|| word.match(/^[Kk]{1}[12]{1}[Ee]{1}[0-9]/g)) {
alert("It matches.");
}
It's identifying that the string does indeed match, even though the prefix is K4E when it should only be either K1E or K2E. 即使前缀为K4E(仅应为K1E或K2E),也可以识别字符串确实匹配。 I'm still a little new to regular expressions, so if you could help me out that would be great.
我对正则表达式还是有点陌生,所以如果您能帮助我,那将很棒。
Thank you for your time! 感谢您的时间!
Rather than [A-Za-z]
, you can just use the i
modifier. 除了使用
[A-Za-z]
,您还可以使用i
修饰符。
You can also collapse the two regular expressions into one with an or clause, |
您也可以使用or子句将两个正则表达式折叠为一个,
|
. 。
My revised regular expression: 我修改后的正则表达式:
/^([A-Z]{1,2}|K[12]E)\d+$/gi
(^[A-Z]{2}\d+$)|(^K[1-2]E\d+$)
这应该工作。
I have a nice tool for you 我有一个好工具给你
http://regex101.com/r/dC2gM3/2 .
http://regex101.com/r/dC2gM3/2 。
To match any number of digits you need a *
at the end. 要匹配任意数量的数字,您需要在末尾加一个
*
。
/^[k][12][e][0-9]*/gi
I do not know, why the alternation
with |
我不知道,为什么
alternation
使用|
does not work as described by the other answerers on this tool... 无法按照此工具上其他答复者的描述工作...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.