4

我只是想创建一个正则表达式来识别文件路径中的图像分辨率。

示例输入字符串可能类似于“/path/to/file/2048x1556/file.type”。

我希望能够匹配的只是“/2048x1556”位。

我不应该说分辨率的数量可以改变,但长度总是 3 或 4 个字符。

到目前为止,我已经尝试过使用:

Pattern.matches("/\\d+x\\d+", myFilePathString)

感觉好像有大约 100 种变化……我是正则表达式的新手,所以我确信这是我忽略的一些简单的东西,但我似乎无法弄清楚。

在此先感谢,马特。

4

3 回答 3

4

You need to use find method..

matches would try to match the string exactly.

find could match in between the string provided you don't use ^,$

See pattern.matcher() vs pattern.matches() for more info


So,your code would be like

boolean isValid=Pattern.compile(yourRegex).matcher(input).find();

But if you want to extract:

String res="";
Matcher m=Pattern.compile(yourRegex).matcher(input);
if(m.find())res=m.group();
于 2013-07-02T14:42:58.993 回答
4

To determine if the filename contains a resolution:

if (myFilePathString.matches(".*/\\d{3,4}x\\d{3,4}.*")) {
    // image filename contains a resolution
}

To extract the resolution in just one line:

String resolution = myFilePathString.replaceAll(".*/(\\d{3,4}x\\d{3,4}).*", "$1");

Note that the extracted resolution will be blank (not null) if there is no resolution in the filename, so you could extract it, then test for blank:

String resolution = myFilePathString.replaceAll(".*/(\\d{3,4}x\\d{3,4}).*", "$1");
if (!resolution.isEmpty()) {
    // image filename contains a resolution
}
于 2013-07-02T14:43:15.963 回答
1

如果你想使用正则表达式,那么

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Test {

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        String regular = "/path/to/file/2048x1556/file.type";

        final String NAME_REGEX = ".*/path/to/file/([^/]+)/";
        System.out.println(runSubRegex(NAME_REGEX, regular));
    }

    private static String runSubRegex(String regex, String tag) {
        Pattern p = Pattern.compile(regex);
        Matcher matcher = p.matcher(tag);
        if (matcher.find()) {
            return matcher.group(1);
        }
        return null;

    }

}
于 2013-07-02T14:50:28.687 回答