【问题标题】:String validation with regex not work使用正则表达式进行字符串验证不起作用
【发布时间】: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


【解决方案1】:

您只匹配单个字符与您的模式,您需要使用*+ 量词匹配零/一个或多个。请注意Matcher#matches() 方法需要完整的字符串匹配。

所以,你需要

pattern = Pattern.compile("[\\s#.$*@+]*")

请注意,您不需要过度转义字符类中的某些字符。

此外,isLineValid 总是返回 false,您需要确保测试该行是否与您的模式匹配的分支将返回 true

Java demo打印“有效”:

import java.util.*;
import java.lang.*;
import java.io.*;
import java.util.regex.*;

class Ideone
{
    public static final Pattern pattern = Pattern.compile("[\\s#.$*@+]*"); // < -- Fixed pattern

    public static void main (String[] args) throws java.lang.Exception
    {
        String s = " #####\n#   ####\n#      #\n### **# #\n#  #* *@#\n#   * ###\n#  ##  #\n##     #\n#.$#  #\n#  ####\n ####";
        if (isLineValid(s)) {
            System.out.println("Valid"); 
        } else {
            System.out.println("Not Valid"); 
        }
    }

    private static boolean isLineValid(String line) {
       if (pattern.matcher(line).matches()) {
          return true;                            // <-- Returning TRUE here
       }
       return false;
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-25
    相关资源
    最近更新 更多