Im working on a project now that has the user enter an RFID which must be a string fixed at 9 characters long and represented in hexadecimal, so each character is either a digit from 0 to 9 or one of the letters A through F. (case insensitive)
Then I also need to take an input of the shelf position which is fixed at 6 characters, the first character is 's' to designate that it is a shelf position and it is followed by a 5 digit number. EX: "s04013" (case insensitive)
Im using a scanner to store the inputs in the variable RFID and originalLocation. I have two questions:
1)How can I check and make sure the input is valid so I can throw an exception if is not? I think I have to use regular expressions but I'm not sure.
2)Is there a way to fix a string's length to a specified amount of characters?
Any help/advice would be greatly appreciated Thank you so much!
(s[0-9]{5}|[0-9a-f]{9})
This regular expression should solve your problem.
String str = "s04013";
String regex = "(s[0-9]{5}|[0-9a-f]{9})";
if(str.matches(regex)) {
/*Do something*/
} else {
throw new Exception("Token does not matach");
}
I dont know if I understand your question correctly but this is what i came up with what i gathered from your question. Code:
import java.util.Scanner;
public class RegexTry {
public static void main(String args[]){
Scanner scanner = new Scanner(System.in);
String RFIDreg = "^[0-9A-Fa-f]{9}$";
String Shelfreg = "^s[0-9]{5}$";
System.out.print("Enter RFID: ");
String RFIDString = scanner.nextLine();//input RFID string
/*Check for RFID string*/
if(RFIDString.matches(RFIDreg)){
System.out.println("Correct");
}
else{
System.out.println("False");
}
/*Check for RFID string*/
System.out.print("Enter Shelf Position: ");
String Shelfstring = scanner.nextLine();//input Shelf string
/*Check for Shelf string*/
if(Shelfstring.matches(Shelfreg)){
System.out.println("Correct");
}
else{
System.out.println("False");
}
/*Check for Shelf string*/
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.