正则表达式匹配key-value
发布时间:2020-12-14 00:43:10 所属栏目:百科 来源:网络整理
导读: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")"; ListString textList = new ArrayListString(); Pattern pattern
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="[^"]*"))"); (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |