java - 我有一个关于 java 的正则表达式模式匹配的问题
问题描述
我想知道正则表达式无法正常工作的原因。
public static void run() {
Scanner strInput = new Scanner(System.in);
String number = strInput.nextLine();
if(getType(number)) {
System.out.println("good");
} else {
System.out.println("");
}
}
//regExp
public static boolean getType(String word) {
return Pattern.matches("^[a-zA-Z]*$", word); //Q1, Q2
}
例如,,
Q1。Pattern.matches("^[a-zA-Z]*$", word);
期望的答案(输入):a+C+a+2+3 -> false
Q2。Pattern.matches("^[0-9|*|+|/|-]*$", word);
期望的答案(输入):1+2/33*4 -> true , 123+333 -> true
对不起,,请理解我英语不好,因为我是外国人..
解决方案
^[a-zA-Z]*$
从头到尾 匹配至少 0 个或多个小写/大写字母。a+C+a+2+3
不满足这些要求,但空字符串可以。^[0-9|*|+|/|-]*$
匹配至少 0 个或多个数字,*
,+
,/
或-
从头到尾;因此也将匹配1+2/33*4
一个空字符串。
因此,这可能是您正在寻找的模式:
public static boolean getType(String word) {
//Match at least 1 or more digits, *, /, +, - from beginning to the end.
return word.matches("^[0-9*\\/+-]+$"));
//This one is even better though. "+1", "1+", will not match
//return word.matches("^([0-9]+[*\\/+-])+[0-9]+$"));
}
推荐阅读
- mysql - 我需要组合 2 个查询,但需要总结其中的一部分
- javascript - Javascript window.location.href.match 不显示代码
- python - 使用 nx.degree_histogram 绘制图的度数分布
- spring - 用spring初始化JMS的MessagingException
- fastlane - 为什么使用 Fastlane 健身房解决 WatchOS 应用程序故障
- pycharm - pycharm一直连接控制台是什么原因
- android - API 请求未从 Android 应用程序获得响应,而 Web 应用程序正在工作
- wso2 - 如何选择 n 号。事件并比较所有事件?
- node.js - 如何测试与硬件相关的功能?
- c++ - 在 GDI 中设置像素的高效方法