Honinbo Shusaku
Honinbo Shusaku

Reputation: 1521

Java better way to code this simple parameter intake?

"Employee identification number (a string) in the format XXX-L, where each X is a digit within the range 0-9 and the L is a letter within the range ‘A’-‘M’ (both lowercase and uppercase letters are acceptable)"

The above is a field which will be an argument for the constructor. Right now, I'm planning on making sure the the first 3 letters of the string is a number between 0-9, and then make sure there is a dash in the index of 4, and then make sure there is a letter between A-M in the 5th index, all using if else statements. Is there a better way of doing this, like if the entering of the parameter didn't have to be so exact, and the programs able to fix it by itself? Thank you.

I coded it and tried regex expression tools:

import java.util.regex.*;

public class Employee {

private String eName;
private String IDNumber;

public Employee(String name, String number) {
    String regex = "[0-9][0-9][0-9][\\-][a-mA-M]";
    Pattern pattern = Pattern.compile(regex);
    Matcher matcher = pattern.matcher(number);
    this.eName = name;
    if(matcher.matches()) {
    this.IDNumber = number;
    } else{
        this.IDNumber = "999-M";
    }

}

public String getNumber() {
    System.out.println(IDNumber);
    return IDNumber;
}

public static void main(String[] args) {
    Employee e = new Employee("John", "123-f");
    e.getNumber();
    Employee c = new Employee("Jane","25z");
    c.getNumber();
}

}

I haven't thoroughly tested it, but it works, but looking at other people's regex expression, mine seems to be very newbish. I was wondering if someone can help me construct a shorter or better regex expression.

Upvotes: 0

Views: 223

Answers (1)

Matt Welson
Matt Welson

Reputation: 268

^\\d{3}-[a-mA-M]$

This should be an improvement I think.

  1. ^ means the start of the text
  2. \d means any digit (backslash itself needs to be escaped)
  3. {3} means previous match 3 times
  4. the hyphen is a literal, as long as it isn't in square brackets
  5. [a-mA-M] means any upper or lower case letter as you knew
  6. $ means the end of the text

I used this site to test it out on regexpal.com

Upvotes: 1

Related Questions