验证String是否与格式String匹配

hpi*_*que 14 java regex string string-formatting

在Java中,如何确定String是否与格式字符串匹配(即:)song%03d.mp3

换句话说,您将如何实现以下功能?

/**
* @return true if formatted equals String.format(format, something), false otherwise.
**/
boolean matches(String formatted, String format);
Run Code Online (Sandbox Code Playgroud)

例子:

matches("hello world!", "hello %s!"); // true
matches("song001.mp3", "song%03d.mp3"); // true
matches("potato", "song%03d.mp3"); // false
Run Code Online (Sandbox Code Playgroud)

也许有一种方法可以将格式字符串转换为正则表达式?

澄清

格式String是一个参数.我不提前知道.song%03d.mp3只是一个例子.它可以是任何其他格式字符串.

如果有帮助,我可以假设格式字符串只有一个参数.

Cep*_*pod 9

我不知道这样做的图书馆.以下是如何将格式模式转换为正则表达式的示例.请注意,Pattern.quote在格式字符串中处理意外正则表达式很重要.

// copied from java.util.Formatter
// %[argument_index$][flags][width][.precision][t]conversion
private static final String formatSpecifier
    = "%(\\d+\\$)?([-#+ 0,(\\<]*)?(\\d+)?(\\.\\d+)?([tT])?([a-zA-Z%])";

private static final Pattern formatToken = Pattern.compile(formatSpecifier);

public Pattern convert(final String format) {
    final StringBuilder regex = new StringBuilder();
    final Matcher matcher = formatToken.matcher(format);
    int lastIndex = 0;
    regex.append('^');
    while (matcher.find()) {
        regex.append(Pattern.quote(format.substring(lastIndex, matcher.start())));
        regex.append(convertToken(matcher.group(1), matcher.group(2), matcher.group(3), 
                                  matcher.group(4), matcher.group(5), matcher.group(6)));
        lastIndex = matcher.end();
    }
    regex.append(Pattern.quote(format.substring(lastIndex, format.length())));
    regex.append('$');
    return Pattern.compile(regex.toString());
}
Run Code Online (Sandbox Code Playgroud)

当然,实施convertToken将是一项挑战.这是一个开始:

private static String convertToken(String index, String flags, String width, String precision, String temporal, String conversion) {
    if (conversion.equals("s")) {
        return "[\\w\\d]*";
    } else if (conversion.equals("d")) {
        return "[\\d]{" + width + "}";
    }
    throw new IllegalArgumentException("%" + index + flags + width + precision + temporal + conversion);
}
Run Code Online (Sandbox Code Playgroud)