简体   繁体   English

字符串中的Java正则表达式字符

[英]Java regular expression characters in a string

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) 我正在处理一个项目,该项目使用户输入一个RFID,该RFID必须是固定为9个字符的字符串,并以十六进制表示,因此每个字符都是0到9的数字或字母A到F中的一个。不敏感)

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. 然后,我还需要输入固定在6个字符上的货架位置,第一个字符是's',表示它是货架位置,后跟5位数字。 EX: "s04013" (case insensitive) EX:“ s04013”(不区分大小写)

Im using a scanner to store the inputs in the variable RFID and originalLocation. 我使用扫描仪将输入存储在变量RFID和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? 1)如何检查并确保输入有效,否则可能引发异常? 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? 2)是否可以将字符串的长度固定为指定的字符数?

Any help/advice would be greatly appreciated Thank you so much! 任何帮助/建议将不胜感激非常感谢!

(s[0-9]{5}|[0-9a-f]{9}) (s [0-9] {5} | [0-9a-f] {9})

This regular expression should solve your problem. 这个正则表达式应该可以解决您的问题。

See DEMO here 在这里查看演示

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*/
}

} }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM