我想知道如何在字符串中查找特殊字符

时间:2015-10-20 15:42:07

标签: java

我在Eclipse中使用Java进行编程,我想要求用户输入他们的特定ID,该ID以大写字母G开头,并且有8位数字。像G34466567。如果用户输入了无效的ID,那将是一个错误。如何将有效身份证与其他身份分开?

3 个答案:

答案 0 :(得分:2)

您可以使用正则表达式。此模式检查第一个字符是否为大写G,并且后面有8个数字:

([G]{1})([0-9]{8})$

如您所见,有两个表达式由()分隔。第一个说“只有一个角色,这个角色必须是大写字母G”。第二个说,必须有8位数字,数字可以是0到9.

每个条件都包含两个“部分”。 []的第一个定义了允许哪些字符。 {}内的模式显示了多少次。 $表示最大长度为9,并且不能有更多字符。

所以你可以阅读这样的条件:

([which chars are allowed]{How many chars are allowed})
^------------------------\/---------------------------^
                    One condition

在Java中你可以这样使用它:

String test= "G12345678";
boolean isValid = Pattern.matches("([G]{1})([0-9]{8})$", test);

如您所见,matches方法有两个参数。第一个参数是regex,第二个参数是要检查的字符串。如果字符串与模式匹配,则返回true。

答案 1 :(得分:1)

创建一个ArrayList。要求用户输入ID,检查列表中是否已存在,忽略,否则将该ID添加到列表中。

编辑:为了确保字符串ID的其余8个字符是数字,您可以使用正则表达式"\\d+"\d代表数字,+代表一位或多位数。

Scanner sc = new Scanner(System.in);
ArrayList<String> IDS = new ArrayList();
char more = 'y';
String ID;
String regex = "\\d+";
while (more == 'y') {
    System.out.println("Pleaes enter you ID.");
    ID = sc.next();
    if (IDS.contains(ID)) {
        System.out.println("This ID is already added.");
    } else if (ID.length() == 9 && ID.charAt(0) == 'G' && ID.substring(1).matches(regex)) {
        IDS.add(ID);
        System.out.println("Added");
    } else {
        System.out.println("Invalid ID");
    }
    System.out.println("Do you want to add more? y/n");
    more = sc.next().charAt(0);
}

答案 2 :(得分:0)

假设您将id保存为字符串,您可以检查第一个字母,然后检查其余字母是否为数字。

实施例

String example = "G12345678";
String firstLetter = example.substring(0, 1); //this will give you the first letter
String number = example.substring(1, 9);  //this will give you the number

要检查该号码是否为数字,您可以执行以下操作,而不是检查每个字符:

try {
      foo = Integer.parseInt(number);
} catch (NumberFormatException e) {
      //Will Throw exception!
      //do something! anything to handle the exception.
      // this is not a number
}