gpt4 book ai didi

java - 验证字符串是否与格式字符串匹配

转载 作者:搜寻专家 更新时间:2023-10-30 19:44:51 24 4
gpt4 key购买 nike

在 Java 中,如何确定字符串是否匹配 format string (即:song%03d.mp3)?

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

/**
* @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

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

澄清

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

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

最佳答案

我不知道有哪个图书馆可以这样做。这是一个如何将格式模式转换为正则表达式的示例。请注意,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());
}

当然,实现 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);
}

关于java - 验证字符串是否与格式字符串匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7189393/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com