正则表达式匹配key-value

前端之家收集整理的这篇文章主要介绍了正则表达式匹配key-value前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

1.先把字符串进行匹配

2.从字符串中得到想要的值

  public void testRegex() {
        String msg = "Rect(x1=\"0\" y1=\"0\" x2=\"416\" y2=\"416\")Rect(x1=\"1\" y1=\"2\" x2=\"413\" y2=\"414\")";
        List<String> textList = new ArrayList<String>();
        Pattern pattern = Pattern.compile("(x1=\"[^\"]*\"\\s*y1=\"[^\"]*\"\\s*x2=\"[^\"]*\"\\s*y2=\"[^\"]*\")");
        Matcher matcher = pattern.matcher(msg);
        while (matcher.find()) {
            textList.add(matcher.group(1));
        }
        for (String text : textList) {
            try {
                System.out.println(text);
                System.out.println(getValue(text,"x1"));
                System.out.println(getValue(text,"y1"));
                System.out.println(getValue(text,"x2"));
                System.out.println(getValue(text,"y2"));
            }
            catch (Exception ex)
            {}
        }
    }

    public static String getValue(String source,String key) {
        if (isEmpty(source)) {
            return null;
        }

        Pattern p = Pattern.compile("\\b" + key + "\\s*=\\s*\"([^\"]*)\"");
        Matcher m = p.matcher(source);
        if (m.find()) {
            return m.group(1);
        }
        return null;
    }
    public static boolean isEmpty(String str) {
        return str == null || str.length() == 0;
    }
输出


注意,匹配到的字符串并不含括号,如果想要匹配括号,那么应该这么写

Pattern pattern = Pattern.compile("(\\(x1=\"[^\"]*\"\\s*y1=\"[^\"]*\"\\s*x2=\"[^\"]*\"\\s*y2=\"[^\"]*\"\\))");

猜你在找的正则表达式相关文章