首页 > 解决方案 > 如果前 3 个位置是字母,如何验证字符串

问题描述

我正在尝试验证用户输入的字符串。用户必须输入一个 7 个字符的字符串;字符串前 3 个字符必须是字母,后 4 个字符必须是数字。

我写了这段代码(作为一个方法),但由于某种原因,它接受第一个字符作为数字(它应该是一个字母),其余的是数字。例如 :

Please enter word : **1gy2345**

这将根据需要进入循环,然后进入 main 中的下一个方法。

如果用户输入一个长度大于 7 的单词,它会要求他输入一个有效的单词。

例如 :

Please enter word : **bob12345**
The word entered is invalid. Please enter a word beginning with 3 letters and ending with 4 numbers ( The word must be 7 characters long ).

这是我的代码:

public static final String solicitationMessage = " Please enter word ";

    public static final String errorMessage = " The word entered is invalid. Please enter a word beginning with 3 letters and ending with 4 numbers ( The word must be 7 characters long ).

    public static final int lengthOfString = 7;

    public static String validateString(String solicitationMessage, String errorMessage, int lengthOfString) {

        System.out.print(solicitationMessage);

        String word = keyboard.nextLine();

        while (!( word.length() == lengthOfString )) {
            if (((word.charAt(0) <= 'a' || word.charAt(0) >= 'z') || (word.charAt(1) <= 'a' || word.charAt(1) >= 'z')
                    || (word.charAt(2) <= 'a' || word.charAt(2) >= 'z'))) {
                System.out.print(errorMessage);
                System.out.print(solicitationMessage);
                word = keyboard.nextLine();
            }
        }
        return word;
    }

但是,如果我输入一个高于 7 个限制字符的字符串,它会再次要求我输入一个有效的字符串,就像它应该做的那样。

不允许使用正则表达式。

有什么帮助吗?

标签: javamethods

解决方案


这是正则表达式的简单任务

[a-zA-Z]{3}[0-9]{4}

一些测试用例:http ://www.regexplanet.com/cookbook/ahJzfnJlZ2V4cGxhbmV0LWhyZHNyEwsSBlJlY2lwZRiAgICi0ZuYCgw/index.html

所以它可能是这样的

Pattern pattern=Pattern.compile("[a-zA-Z]{3}[0-9]{4}");
String line;
while(true){
   line= keyboard.nextLine();
   if(pattern.matcher(line).matches()){
     break;
}
}

推荐阅读