I'm using the following code using Java 7 to validate the format of a file:
private boolean validateFile(String image) {
// Get width and height on image
...
...
//Multiply by three, once for each R,G, and B value for the pixel
int entriesRequired = width * height * 3;
Pattern pattern = Pattern.compile("w=\\d+\\s+h=\\d+\\s+OK\\s+[\\d+\\s+]{" + entriesRequired + "}");
Matcher matcher = pattern.matcher(image);
return matcher.matches();
}
The file, which I've read into a String and is being held by the image
variable, appears as so:
"w=1\nh=2\nOK\n1\n2\n3\n4\n5\n6\n"
I'm expecting validateFile(String image)
to return True, but it's been returning false. Any regex experts out there who can help me out?
Thanks, Josh
Your regex is wrong.
"w=\\d+\\s+h=\\d+\\s+OK\\s+[\\d+\\s+]{" + entriesRequired + "}"
[\\\\d+\\\\s+]{n}
Means "String of length n
created using any of \\d
, \\s
, +
."
What you want is \\d+\\s+
repeated n times, so change the brackets to parenthesis:
"w=\\d+\\s+h=\\d+\\s+OK\\s+(\\d+\\s+){" + entriesRequired + "}"
It works for me
Side note: in that particular case you don't need Pattern
and Matcher
, you can just use
image.matches("w=\\d+\\s+h=\\d+\\s+OK\\s+(\\d+\\s+){" + entriesRequired + "}");
Since your regex validates the entire string
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.