如何检查字符串是否与特定格式匹配?

时间:2021-04-02 23:14:47

标签: java

我想知道如何检查字符串格式是否匹配

“111 + 222”

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

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

我知道我应该使用匹配来做到这一点,但我如何用空格处理它?<​​/p>

1 个答案:

答案 0 :(得分:2)

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

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);
}
相关问题