java - 如果前 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 个限制字符的字符串,它会再次要求我输入一个有效的字符串,就像它应该做的那样。
不允许使用正则表达式。
有什么帮助吗?
解决方案
这是正则表达式的简单任务
[a-zA-Z]{3}[0-9]{4}
所以它可能是这样的
Pattern pattern=Pattern.compile("[a-zA-Z]{3}[0-9]{4}");
String line;
while(true){
line= keyboard.nextLine();
if(pattern.matcher(line).matches()){
break;
}
}
推荐阅读
- django - 如何获得书籍 django 的总价?
- javascript - Javascript - 仅在美国东部标准时间上午 9 点以下时允许
- swift - 如何访问 usdz modelComponent 中的特定关节
- sql - Hive 中 TO_CHAR(在 Oracle SQL 中)的等效函数
- c# - C#:递归方法期间的堆栈溢出异常
- r - 问题在离散数据上绘制连续数据,然后根据另一个离散数据使用线
- python - 将列表中的所有数据放入单独的 tkinter 标签
- python - 如何在满足if语句的循环内为列表中的每个项目保留单独的计数
- java - 递归调用导致 Java 堆栈溢出
- python - 在 pyqt5 中使用鼠标滚轮在 QGraphicsScene 上缩放图像