Nikolas Alg Nikolas Alg - 1 month ago 6
Java Question

String validation with regex not work

I need validate game levels in text file in follow format:

#####
# ####
# #
### **# #
# #* *@#
# * ###
# ## #
## #
#.$# #
# ####
####


Here is my Java code:

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;
}


Whats wrong with my regex? Because I allways get false. Thanks

Answer

You only match a single character with your pattern, you need to match zero/one or more with * or + quantifiers. Mind that the Matcher#matches() method requires a full string match.

So, you need

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

Note that you do not need to overescape certain chars inside a character class.

Besides, the isLineValid always returns false, you need to make sure one branch that tests if the line matches your pattern will return true.

See Java demo printing "Valid":

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;
    }
}