简体   繁体   English

Javascript RegEx匹配字符串

[英]Javascript RegEx to Match Against a String

I need to identify strings that have the exact templates (can be either of the two): 我需要确定具有确切模板的字符串(可以是两个模板之一):

  1. 1 OR 2 Characters (AZ) and then followed by a number (doesn't matter how many digits). 1个或2个字符(AZ),然后跟一个数字(与多少个数字无关)。
  2. K1E OR K2E and then followed by a number (also doesn't matter how many digits). K1E或K2E,然后跟一个数字(无论多少位也无所谓)。 The letter 'K' and then a '1' OR '2' and then followed by an 'E' is strictly how the string should begin. 字母“ K”,然后是“ 1”或“ 2”,然后是“ E”,严格来说是字符串的开头方式。

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.

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