【发布时间】:2016-10-31 10:46:33
【问题描述】:
我需要在以下格式的文本文件中验证游戏关卡:
#####
# ####
# #
### **# #
# #* *@#
# * ###
# ## #
## #
#.$# #
# ####
####
这是我的 Java 代码:
static Pattern pattern = Pattern.compile("[\\s#.$*@+]");
static BufferedReader br;
public static void main(String[] args) {
...
while ( (x = br.readLine()) != null ) {
System.out.println(x.toLowerCase());
System.out.println(isLineValid(x));
} ... }
private static boolean isLineValid(String line) {
if (pattern.matcher(line).matches()) {
return true;
}
return false;
}
我的正则表达式有什么问题?因为我总是假的。谢谢
【问题讨论】:
-
当您在 isLineValid() 中的任何情况下返回 false 时,所有情况下都为 false。
-
为什么你只返回 pattern.matcher(line).matches() ?
-
但问题是为什么......我总是只有这七个字符......
-
这里有多个问题:1)
matches()需要完整的字符串匹配,因此模式必须是Pattern.compile("[\\s#.$*@+]*"),2)isLineValid总是返回 false,必须变成if (pattern.matcher(line).matches()) { return true; } -
在这两种情况下你只会返回 false
标签: java regex pattern-matching