首页 > 解决方案 > 如何检查字符串是否匹配特定格式?

问题描述

我想了解如何检查字符串格式是否匹配

“111 + 222”

使用这样的字符串,格式应该是

(double type number)+(white space)+(operand(+,-,*,/,^))+(white space)+(double type number)

我知道我应该使用匹配来做到这一点,但我该如何处理这个与空白?

标签: java

解决方案


是的,您可以使用模式匹配器或字符串匹配。

public static void main(String[] args) throws Exception {
    String pattern = "-?[\\d\\.]{3,4}\\s[+\\-*/^]\\s-?[\\d\\.]{3,4}";
    System.out.println(matchWithPatternMatcherCompile(pattern, "111 + 222")); // True
    System.out.println(matchWithPatternMatcher(pattern, "111 + 222")); // True
    System.out.println(matchWithStringRegex(pattern, "111 + 222")); // True
    System.out.println(matchWithPatternMatcherCompile(pattern, "111 + -2.22")); // True
    System.out.println(matchWithPatternMatcher(pattern, "11.1 + 222")); // True
    System.out.println(matchWithStringRegex(pattern, "-111 + 222")); // True
}

private static boolean matchWithStringRegex(String regex, String input) {
    return input.matches(regex);
}

private static boolean matchWithPatternMatcherCompile(String regex, String input) {
    Pattern pattern = Pattern.compile(regex);
    Matcher matcher = pattern.matcher(input);
    return matcher.matches();
}

private static boolean matchWithPatternMatcher(String regex, String input) {
    return Pattern.matches(regex, input);
}

推荐阅读