0

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!

5
  • 1
    Your first regular expression matches: "K4" is a letter followed by a digit. Probably the {1,2} in the first regex should just be {2} Commented Aug 21, 2014 at 15:57
  • Your regex is too broad, if you're only trying to match K1 or K2. Try /^[A-Za-z]{1,2}[12]/ And are you really OK matching one or two letters at the beginning? Commented Aug 21, 2014 at 15:58
  • @Pointy Apologies, it is actually one or two letters at the beginning in the first template. Didn't accurately note that. I will make the change now. Thanks! Commented Aug 21, 2014 at 16:03
  • @vch It is actually 1 or 2 letters! Should have triple checked that everything was okay before submitting the question. Commented Aug 21, 2014 at 16:05
  • @Kellowyn well in that case the word "K4E43057" should match, right? It starts with a letter followed by a digit. Commented Aug 21, 2014 at 16:06

3 Answers 3

1

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
Sign up to request clarification or add additional context in comments.

1 Comment

My mistake. It is actually one OR two letters. Made the revision above.
0
(^[A-Z]{2}\d+$)|(^K[1-2]E\d+$)

This should work.

Comments

0

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

1 Comment

You are welcome. Actually found by @TJCrowder. Big respects!!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.