-6

I need regex patterns for the AANNN and ANEE formats.

  • A means letters
  • N means digits
  • E means either letters or digits.

I need to validate input strings according to these formats.

Examples

  • BD123 matches the AANNN
  • G21H matches the ANEE
zx81
  • 38,175
  • 8
  • 76
  • 97
Kal
  • 25
  • 5

1 Answers1

1

I'm assuming you want ASCII letters and digits, but not Thai digits, Arabic letters and the like.

  1. AANNN is (?i)^[a-z]{2}[0-9]{3}$
  2. ANEE is (?i)^[a-z][0-9][a-z0-9]{2}$

Explanation

  • The ^ anchor asserts that we are at the beginning of the string
  • [a-z] is what's called a character class. It allows any chars between a and z.
  • In a character class we can include several ranges, that's why the E is [a-z0-9]
  • Normally for A you would have to say something like [a-zA-Z], but the (?i) flag makes it case-insensitive
  • {2} is a quantifier that means "match the previous expression twice
  • The $ anchor asserts that we are at the end of the string

How to Use

In Java, you can do something like:

if (subjectString.matches("(?i)^[a-z]{2}[0-9]{3}$")) {
    // It matched!
    } 
else {  // nah, it didn't match...  } 

Regular Expressions are Fun! I highly recommend you go learn from one of these resources.

Resources

Community
  • 1
  • 1
zx81
  • 38,175
  • 8
  • 76
  • 97
  • Depends on the Java method the OP uses, but I would like to see anchors, otherwise you could get matches on parts of a string. – stema Jun 25 '14 at 09:12
  • @stema Yes, you're dead right—an oversight, in your place I would be writing the same comment. Fixed and added explanation, thank you. :) – zx81 Jun 25 '14 at 09:15
  • Thanks for info, i got the concept as well,surely i will go through the references to learn about regex patterns. – Kal Jun 25 '14 at 09:17
  • Thanks, glad it worked! FYI, just added some Java code. :) – zx81 Jun 25 '14 at 09:21
  • FYI: reformatted your question. Have a look. IMO a question has a better chance if it is presented in a clear way like that... It got severely downvoted! See you next time. :) – zx81 Jun 25 '14 at 09:26