简体   繁体   English

量词的Java正则表达式问题

[英]Java Regex Issue with Quantifiers

I'm using the following code using Java 7 to validate the format of a file: 我使用Java 7使用以下代码来验证文件格式:

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: 我已将其读入String并由image变量保存的文件显示如下:

"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. 我期望validateFile(String image)返回True,但是一直返回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 , + ." [\\\\d+\\\\s+]{n}意思是“使用\\d\\s+任何一个创建的长度为n字符串。”

What you want is \\d+\\s+ repeated n times, so change the brackets to parenthesis: 您想要的是\\d+\\s+重复n次,因此将括号更改为括号:

"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 旁注:在特定情况下,您不需要PatternMatcher ,只需使用

image.matches("w=\\d+\\s+h=\\d+\\s+OK\\s+(\\d+\\s+){" + entriesRequired + "}");

Since your regex validates the entire string 由于您的正则表达式会验证整个字符串

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM