首页 > 解决方案 > 数学表达式中的字符串匹配 x <= 900 (int, int)

问题描述

我有数字,比如 900。"x <= int (int, int)"例如,我提取了一个格式为的字符串。"x <= 900 (4, 7)" 我想验证它是否与格式匹配"x <= 900 (int, int)"

如何使用字符串模式匹配器来做到这一点?

到目前为止,我已经尝试了以下方法,结果是错误的。

1)        Pattern pattern = Pattern.compile("x <= 900 (\\d, \\d)");
2)        Pattern pattern = Pattern.compile("x <= 900 ([0-9], [0-9])");

        String expectedString = "x <= 900 (4, 7)";

        Matcher m = pattern.matcher(expectedString);
        System.out.println(m.matches());

标签: javaregex

解决方案


您需要使用反斜杠 ( \) 转义括号,因为它们是正则表达式元字符。要匹配一位或多位数字,请使用\d+.

Pattern pattern = Pattern.compile("x <= \\d+ \\(\\d+, \\d+\\)");

Demo


推荐阅读