user3813995
user3813995

Reputation:

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 (A-Z) and then followed by a number (doesn't matter how many digits).
  2. K1E OR K2E and then followed by a number (also doesn't matter how many digits). The letter 'K' and then a '1' OR '2' and then followed by an 'E' is strictly how the string should begin.

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. 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!

Upvotes: 0

Views: 71

Answers (3)

Schism
Schism

Reputation: 275

Rather than [A-Za-z], you can just use the i modifier.

You can also collapse the two regular expressions into one with an or clause, |.

My revised regular expression:

/^([A-Z]{1,2}|K[12]E)\d+$/gi

Upvotes: 1

user32342534
user32342534

Reputation: 145

I have a nice tool for you

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 | does not work as described by the other answerers on this tool...

Upvotes: 0

vks
vks

Reputation: 67968

(^[A-Z]{2}\d+$)|(^K[1-2]E\d+$)

This should work.

Upvotes: 0

Related Questions