验证String是否与格式String匹配

验证String是否与格式String匹配

本文介绍了验证String是否与格式String匹配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Java中,如何确定String是否与(即:歌曲%03d.mp3 )?

In Java, how can you determine if a String matches a format string (ie: song%03d.mp3)?

换句话说,如何你会实现以下函数吗?

In other words, how would you implement the following function?

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

示例:

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

也许有办法将格式字符串转换为正则表达式?

Maybe there's a way to convert a format string into a regex?

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

The format String is a parameter. I don't know it in advance. song%03d.mp3 is just an example. It could be any other format string.

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

If it helps, I can assume that the format string will only have one parameter.

推荐答案

我不知道这样做的库。以下是如何将格式模式转换为正则表达式的示例。请注意, Pattern.quote 对于处理格式字符串中的意外正则表达非常重要。

I don't know of a library that does that. Here is an example how to convert a format pattern into a regex. Notice that Pattern.quote is important to handle accidental regexes in the format string.

// 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());
}

当然,实施 convertToken 将是一个挑战。下面是一些事情:

Of course, implementing convertToken will be a challenge. Here is something to start with:

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

这篇关于验证String是否与格式String匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-15 00:53